If in javascript object properties are passed by reference why this doesnt work:
var myObj={a:1}
function myFun(x){
x=2;
}
myFun(myObj.a);
// value myObj.a is still 1
but on the other hand if you do this:
var myObj={a:1}
function myFun(x){
x.a=2;
}
myFun(myObj);
// this works myObj.a is 2
Primitive values are passed by value. Objects are passed by reference.
Object properties are passed by based on their data type.
Here you are passing an integer –
xrepresents the value 1. Assigningxthe value 2 does not reference the original object.Let’s say the property you pass in is an array. And the 2nd function I call receives an array and you make changes to that array. Then the changes will persist to the object because the object’s property contains a reference to the array you modified. You didn’t technically modify the object at all… you just modified the array which is referenced in the object. When you pass an object property to a function, it’s not aware that it belongs to an object at all.
See example, similar to yours: