JavaScript pass by reference and pass by value.
This post is about pass by value and pass by reference in JavaScript. Before going into a topic we need to recall things.
In the major programming language, there are two types of data types.
- Primitive
- Non-primitive
Primitive
Primitive are predefined datatypes. They are immutable. In JavaScript the primitive data types are
1.Boolean
2.null
3.undefined
4.Number
5.String
Get Vishnuraj’s stories in your inbox
Join Medium for free to get updates from this writer.
6.Symbol
Non-Primitive
non-primitive datatypes are user define data type. they are mutable in general. In JavaScript Object is Non-Primitive. It is widely used in JavaScript.Objects are defined as key-pair value.
pass by value
All the primitive data types in JavaScript are pass by value in nature. Their value won’t change if we pass as a parameter to function.
let orig=0;
let copy;
copy=orig;
copy=1;
console.log(orig,copy);//0,1 In the above code the variable copy creates new memory assigns the value. therefore there is no contact between orig and copy.
pass by reference.
Object are pass by reference in JavaScript. when you assign an object to another variable it won’t create new memory. instead it just refer to original object memory.
let obj={"value":10};
let obj1=obj;
obj1.value = 20;
console.log(obj.value) //20In the above code an object is defined in obj and assigned to obj1. whenever obj1 value got changed it also affect obj. Even the changes made in obj will affect the variables refer to obj.
//continue to previous code
obj={"reference":true};
console.log(obj,obj1) //{reference: true} {reference: true}Note: only the data inside the object is non-primitive not the variable.
//it won't work
let a={"test":100};
let b=a;
let c=b;b={"test":101};
console.log(a,b,c) //{test:100} {test:101} {test:100}
So how to prevent from Pass by reference.
There are few tricks to prevent an object from being pass are reference.
- Object.assign()
- JSON.stringify()
- Spread syntax
Object.assign (ES2016)
let obj={"a":1,"b":2};
let obj1=Object.assign({},obj);
obj1.a=100;
console.log(obj,obj1) // {a:1,b:2} {a:100,b:2}JSON.stringify
let obj = {"a":1,"b":2};
let obj1 = JSON.parse(JSON.stringify(obj));
obj1.a = 100;
console.log(obj,obj1) // {a:1,b:2} {a:100,b:2}Spread syntax (ES2018)
let obj = {"a":1,"b":2};
let obj1 = { ...obj };
obj1.a = 100;
console.log(obj,obj1) // {a:1,b:2} {a:100,b:2}Some library like underscores have functions to clone…



