Clone an array without reference - JavaScript Basics Tips #Day1

Clone an array without reference - JavaScript Basics Tips #Day1

ยท

1 min read

Hey everyone, in a new approach I will be posting daily articles for the basics in JavaScript which will be unique and be helpful to the readers.

Today, we will look at how to clone an array without mutating the original array or referring to it. This will be helpful in the areas of Functional Programming where the original object needs to be not mutated.

This is achieved using the spread operator.

Spread Operator

The spread operator allows an iterable object to expand where multiple arguments are required. The syntax of the spread operator is

var variable = [...value1]

It allows us to have the privilege of using all the list parameters from an array. It can be used to expand, concat, copy, and also with math objects. It can be used for performing the computation in objects as well.

Clone the array

var originalArray = [1,2,3,4] //Original Array 
var copyArray = [...originalArray] //Copy of the original Array using spread operator

That's all !! You have your copied array with its own reference to it. Hope you like this small information bites and will see you in the next article.

Like and follow for more articles like these. Post your thoughts and ideas in the comments ๐Ÿ˜‰