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 flash and 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?
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) x.
This article was originally published on medium
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.