I was trying to understand passing of variables and objects in JavaScript, and came across this page.
It is explained that JavaScript objects are passed by value, but the value itself is a reference. Though I understood what was happening in the examples given on that page, I am still confused so as to why. Can anyone please explain what does “value itself is a reference” mean?
Some languages have a “pass by reference” concept for function arguments which means that when you call a function and pass in a variable by reference the function can modify the original variable to hold some other value – it has a reference to the original variable.
With “pass by value” when you call a function and pass in a variable the function only gets the value so can’t change the original variable that was passed in.
JS only has “pass by value”, however when you pass an object as a parameter the “value” is a reference to the original object such that the function can modify, create or delete properties of that object, but the function can’t modify the original variable to refer to some other object or value.
Example:
The code I’ve shown creates a variable,
o, that references an object withaandbproperties. It then calls the functionchangeObjand passes ino. The function changes the value of theaproperty and creates a newcproperty – the function is modifying the same object that variableorefers to because it has a reference to that object. But then the function assignssomeObjequal to a completely new object. This does not affectoat all because the function only had a reference to the objectowas pointing at, it didn’t have access to theovariable itself.