How arrays and objects are copied in JavaScript?

First, we need to thoroughly understand two concepts.

  1. Pass by value.
  2. Pass by reference.

Pass by value

It simply means, While calling a function. You are passing values directly inside a function as an argument.

EG:

// function declaration
function greet(name){
    console.log(`hello ${name}!`);
}

// function calling
greet("Hemendra");// <- we're passing value as an argument

// prints --> hello Hemendra!

Pass by reference

It simply means, While calling a function, You will pass a reference of a constant or a variable instead of a value directly inside a function as an argument.

EG:

// function declaration
function greet(name){
    console.log(`hello ${name}!`);
}

const name = "Hemendra";

// function calling
greet(name); // <-- we're passing a reference of a constant called name  

// prints --> hello Hemendra!

Pretty simple right?

Yes, it's that simple!

But, there is more to understand here. Let's understand this by an example.

EG:1

// You might have written something like this before

let score = 10;
let temp = score;
temp = temp + 2;

console.log(`score is ${score}`); // prints-> score is 10
console.log(`temp is ${temp}`); // prints-> temp is 12

EG: 2

// You might have done something like this as well

let todos = ["T1", "T2];
let tempTodos = todos;
tempTodos.push("T3");

console.log(`old todos are ${todos}`); 
// prints-> old todos are T1, T2, T3
console.log(`temp todos are ${tempTodos}`); 
// prints-> temp todos are T1, T2, T3

Wait whatttttt??

confusion

Yes, I was also like this when I was a beginner. Let's understand what just happened in the above example.

Remember this

  • While working with primitive data type in JavaScript we copy its value.

EG: string, number, boolean, symbol, undefined, null.

  • While working with non-primitive data type in JavaScript we copy its reference.

EG: arrays, objects, functions

Explanation

In the first example, we used the primitive data type which is why the score and temp variable's value was different.

But, In the second example, we used an array that was a non-primitive data type, and while copying the variable, we have reference of it instead of its value. Hence both the variables todos and tempTodos were pointing to the same value in the memory.

Thus, while changing the tempTodos variable todos variable was also changing.

Tip:

We often encounter an array of objects while building any application. We create multiple functions to modify the array of objects.

But do remember this concept,

How array or objects are copied in JavaScript. Else you will end up facing a lot of bugs in your app.


follow me for more such blog posts.

Let me know if this blog was helpful.

Did you find this article valuable?

Support Hemendra Khatik by becoming a sponsor. Any amount is appreciated!