The Domino Effect: Call by Reference

What is Call by Reference?

Ok in simple words when you copy from someone else and he changes his answer because of this now you also have to change your answer. Similarly in programming, when you have multiple variables that reference the same object in memory, changes made to the object through one variable will be reflected in all the other variables referencing that object.

For example:

let myName = {name:'atharva'}
let myName1 = myName
let myName2 = myName1

myName2.name = 'Arthur Senpai'
console.log(myName)// Arthur Senpai
console.log(myName1)// Arthur Senpai
console.log(myName2)// Arthur Senpai

Why does this happen?

When a variable is assigned to another, it retains the reference, creating a link between them. Consequently, modifications made to the new variable impact the original one, as both variables share the same reference. This behavior is a result of the reference-based storage mechanism, influencing the values accessed through either variable. Understanding this linkage is crucial for managing data consistency and avoiding unintended side effects in your code.

How to fix it?

Shallow Copy:

A shallow copy creates a new object but doesn't create copies of nested objects within it. Instead, it copies references to the nested objects. Consequently, changes made to nested objects in the copied structure affect the original and vice versa.

let myName = { name: 'atharva' };
// Shallow copy using the spread operator
let myName1 = { ...myName };
let myName2 = { ...myName1 };

myName2.name = 'Arthur Senpai';

console.log(myName);   // { name: 'atharva' }
console.log(myName1);  // { name: 'atharva' }
console.log(myName2);  // { name: 'Arthur Senpai' }

Deep Copy:

A deep copy creates a completely independent copy of the original object along with copies of all nested objects. This means that changes made to the copied structure do not affect the original, and vice versa.

let myName = { name: 'atharva' };
// Deep copy using JSON.parse and JSON.stringify
let myName1 = JSON.parse(JSON.stringify(myName));
let myName2 = JSON.parse(JSON.stringify(myName1));

myName2.name = 'Arthur Senpai';

console.log(myName);   // { name: 'atharva' }
console.log(myName1);  // { name: 'atharva' }
console.log(myName2);  // { name: 'Arthur Senpai' }

Note: JSON.parse(JSON.stringify()) the method has limitations and won't work correctly for objects containing functions, circular references, or other non-JSON-serializable elements. In such cases, using a dedicated library for deep cloning, like Lodash's _.cloneDeep, is recommended.

Delighted that you enjoyed the blog! Your support means the world ❤️🌟. Stay tuned for more exciting content and updates—your presence makes it all the more special! 🤗📚 #FollowForMore

Did you find this article valuable?

Support Atharva Mulgund by becoming a sponsor. Any amount is appreciated!