All Articles

Copying the correct way in js

In this blog we will deep dive various possible ways by which we can create a copy of a variable, object, array or nested structure in javascript.

Lets us start with the simplest way of copying a value which is the assignment operator.

The Assignment Operator ( = )

Its so easy to copy or assign a value to another object by using the = operator.

let originalVar=1
let copyVar = orignialVar
console.log(copyVar) OUTPUT-->1

As you saw that the changes in value of originalVar caused no changes in its copy, so assignment operator work fine when you are copying primitive values.

Now let us consider an object and copy it using assignment operator.

let originalObj = {a:1}
let copyObj = originalObj
console.log(copyObj) OUTPUT-->{a=2}

So this time change in orignal object caused changes in other, so the first thumb rule, assignment operator will cause the value of other identifier to change if the value copied to it is non primitive and is changed.

Do you know array is also of type object in js, so you are smart enough to understand how copying with this technique will work with it.