Why primitive values are assigned by value and non primitive values by reference in JavaScript?
Assigning or copying content of primitive types and non primitive types behave completely different. Before understanding what made it behave differently, let us understand briefly about primitive types and non primitive types.
Primitive vs Non Primitive
All the data types in javascript fall under two categories named primitive data types and non primitive data types(also known as object references or complex data types or composite data type). Primitive values in JavaScript are numbers, strings, booleans, null, undefined. Objects such as functions and arrays are referred to as non-primitive values.
When a primitive value is assigned to a variable (eg let name = ‘Mike’), the variable is set to that value directly. But when the non primitive value i.e object is assigned to a variable, first the object is stored somewhere in computed memory and then a reference to that memory containing the object is set to that variable.
This difference in behavior affects how variable assignments are made, how equality operators get their results, and how JavaScript programs run in general.
Copying content in Primitive types Vs Non Primitive types
So far,we have learned that variables set to primitive values contain actual values, and variables set to non primitive values just contain references (or memory addresses).
Let’s look at an example of each to explore how this fact affects the behavior of variable assignments. In the example1, bookName is assigned to movieName in line2. Updating the value stored in bookName in line 5 does not affect the value stored in movieName as bookName and movieName are primitive types
In the example2, an object with name and author as properties is created in memory and a reference to this memory is assigned to the variable book in line1. Now variable book which holds the reference of the object is assigned to new variable movie in line5. When name property is updated in line6, it is actually updating in the object stored in the memory, not in the object book directly. Understand this point to make the whole picture clear. As both book and movie holds reference to the same object, both the name properties are updated.
Refer my other blog for assigning an object that holds reference of a different memory address here