https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language?rq=1
Javascript parameters are pass by value, the value is that of the reference address.
1 2 3 4 5 6 7 8 9 |
function changeStuff(numParam) { numParam.item = "changed"; // dereferences } var obj1 = {item: "unchanged"}; // object with item as property changeStuff(obj1); console.log(obj1.item); |
obj1 is a reference that points to the object. Specifically, it points to the address of the object.
In the function changeStuff, its parameter ‘numParam’ is pushed as a reference on to the local function stack. It then copies by value the address of the object pointed to by obj1.
Parameter reference dereferences the object
Inside changeStuff, when we access the property item, our reference would dereference the object and get the value of item. Then assign it a new value “changed”. That’s why when the function finishes and pops, our obj1 reference outside will see that its property item was dereferenced and changed to “changed”.
1 |
numParam.item = "changed"; // dereferences |
Simply points away
The other situation is that we assign our parameter reference to another object. When this happens, we point our reference away from the object that obj1 points to, and onto the new object. That’s why when our function exits, the obj1 still points to its own object and the item property is still “unchanged”
1 2 3 4 5 6 7 8 9 |
function changeStuff(numParam) { numParam = {item: "changed"}; // points away } var obj1 = {item: "unchanged"}; // object with item as property changeStuff(obj1); console.log(obj1.item); |
Primitives – Pass by Value
In JavaScript there are 5 primitive types: undefined , null , boolean , string and number. They are all passed by value.
1 2 3 4 5 6 7 8 |
function changeStuff(a) { a = 88; } var num = 10; changeStuff(num); console.log(num); // 10 |