Copying Reference Type Value in Js

Copying Reference Type Value in Js

·

3 min read

// Copying Value:
let a = 10;
let b = a; // 10
b = b + b; // 20
// Expected behaviour!!
// Now, What's the behaviour of this:
let x = [1, 2, 3, 4];
let y = x; 
y.pop(); // [1, 2, 3]
// Simple but what's in x - [1, 2, 3] 
// How? Let's know how?

First of all, what are the 2 types of data? primitive and reference types.

What is the Primitive Type?

Primitive types are the basic data types that are stored directly in the variable. They include numbers, strings, booleans, and null.

What was going on in the first code?

Here, We are Copying value in Primitive type, which is directly copying the value to the desired variable.

let a = 10;
let b = a; // 10
b = b + b; // 20

What is the Reference Type?

Reference types are objects that are stored in memory and accessed through a reference. They include arrays, objects, and functions.

What was going on in the second code?

Here, We are copying the references of the values. We are not duplicating the values of the array of x in y but storing the reference of values.

let x = [1, 2, 3, 4];
let y = x; 
y.pop(); // [1, 2, 3]
// x = [1, 2, 3]

By copying values directly like y = x and manipulaing y will further result in changing values of the source variable, which is x in our example, that is because of reference type values.

How values are stored?

Array's Actual Values: [1, 2, 3, 4] --> stored in memory, somewhere.

x --> stores the reference of the array

y --> stores the value of x (which is reference value) = stores the reference of array

values inside (), [], {}; Behave in the same manner mentioned above. Copying the reference, not the actual value.

How to Copy in reference type?

To copy, In reference type, The most easy and simple one is to use the spread operator: ...

let x = [1, 2, 3, 4];
let y = [...x]; 
y.pop(); // [1, 2, 3]
// x = [1, 2, 3, 4]

Spread operator act as a placeholder for the values that comes from the source variable that is mentioned after spread operator.

Example using object

let obj = {name: "Mansi", msg: "Follow me for more blogs!"};
let copyObj = {...obj}; //{name: "Mansi", msg: "Follow me for more blogs!"}

Thank You for reading! don't forget to drop your valuable feedback and suggestions in the comments.

Author: Mansi Dass🤍

Did you find this article valuable?

Support Mansi dass by becoming a sponsor. Any amount is appreciated!