In javascript, primitive values are passed by value and objects are passed by reference.
So what do we mean by pass by value and pass by reference.
pass by value
var music1 = ‘blues’; var music2 = music1; music1 = ‘jazz’; console.log(music1); // jazz console.log(music2); // blues
Here we assigned string “blues” to variable music1 and assigned music1 to music2. After that we reassigned variable music1 to ‘jazz’ so when we console log music1 we get jazz but when we console log music2 we get ‘blues’. The value held by music2 remains unchanged.
This is because when we assigned primitive values to variable
- variable gets the copy of primitive value
- variable actually holds the value
- copy of value is placed in memory where variable is stored
So in our example, variable music1 gets the copy of string value ‘blues’ and when we assign variable music1 to music2, music2 also gets its own copy of string value ‘blues’. This is called pass by value.
Although music1 and music2 hold same value, they have their own unique location in memory. When you change value of one variable it does not affect other variable. Hence, in our example when we changed the value of music1 from ‘blues’ to ‘jazz’ it did not affect music2. Value of music2 is still ‘blues’.
pass by reference
When we assign object to a variable, variable does not hold the object. It will only refer to the point in memory where object is stored. It does not get copy of object like primitive values. This is called pass by reference.
var music1 = { genre: ‘blues’, instrument: ‘guitar’ } var music2 = music1;
Here in our example when we assign object to variable music1, it does not contain the object but rather it is only reference point to where the object is stored in memory space.
And when we assign music1 to variable music2, both the variables will point to the same location in memory. Variable music2 does not point to a new location in memory.
music1.genre = 'jazz'; console.log(music1); // { genre: 'jazz', instrument: 'guitar' } console.log(music2); // { genre: 'jazz', instrument: 'guitar' }
Here we have changed the property of music1 genre from ‘jazz’ to ‘blues’. Since both of theses variables point to same location in memory when we mutate music1 we can see changes in music2 also.
Consider this example below.
avenger1 = { name: 'hulk' } avenger2 = { name: 'hulk' } console.log(avenger1 === avenger2); // false
Here we have two objects with same properties(key value pair) but when we compare them we get false because they don’t point to same location in memory. Each object has it’s own separate storage address in memory.