- The typeof value assigned to a variable decides whether the value is stored with assign-by-value or assign-by-reference
- On variable assignment, the scalar primitive values (Number, String, Boolean, undefined, null, Symbol) are assigned-by-value and compound values (Object, Array) are assigned-by-reference
Quick example on assign-by-value:
In the code snippet below, we are assigning scalar primitive value (number) to a variable and thus assign-by-value applies here. Firstly, the variable
batman is initialized and when the variable
superman is assigned with the value stored in variable
batman, it creates a new copy of the value and stores it. When the variable
superman is modified, variable
batman is left unaffected as they point to distinct values.
Quick example on assign-by-reference:
In the code snippet below, we are assigning a compound value (array) in a variable and thus assign-by-reference applies here. The variables
quicksilver are references to the same value (aka shared value). The references will point to the updated value when the shared value is modified .
How to create a new reference?
How references work when values are passed as function parameters?
In the code snippet below, variable
magneto is a compound value (Array object), thus it is assigned in variable (function argument)
x with assign-by-reference. The
Array.prototype.push method invoked inside IIFE mutates the value in variable
x creates a new reference, and further modifications on it does NOT affect the reference to variable
The solution here would be to modify the existing compound value where the reference is pointing to. In the code snippet below, variable
wolverine is a compound value (Array object) and on IIFE invocation, variable (function argument)
x is assigned by reference. The
Array.prototype.length property can be used to create an empty array by setting its value to
0. Thus, variable
wolverine is changed to the new value set in variable
How to store a compound value through assign-by-value?
The solution here would be to make a manual copy of the compound value and then assign the copied value to a variable. Therefore, the reference of assigned value does NOT point back to the original value. The recommended approach to create a (shallow) copy of the compound value (Array object) is to invoke
Array.prototype.slice method on it with no arguments passed.
How to store a scalar primitive value through assign-by-reference?
The solution here would be to wrap scalar primitive value in a compound value (Object, Array) as its property value. Thus, it can be assigned-by-reference. In the code snippet below, scalar primitive value in variable
speed is set as a property on object
flash. Therefore, it is assigned-by-reference on IIFE invocation to variable (function argument)
Are you new to Linux and wants to do Linux Command Line? Get my Udemy course on “Linux Command Line for Beginners” at a discount price (limited offer) by clicking here.