How to do pass by reference in JavaScript?
In the JavaScript world, it is always passed by value. But in the case of objects, the value of the variable is a reference. This is why, when we pass an object and change its property, those changes persist outside of the function. This makes it look like objects are passed by reference.
So in JavaScript, it feels like:
Primitives are passed by value, and objects are passed by reference.
Let’s consider the following example:
Example using object:
function update(obj) { obj.name = 'Ane'; } const user = {name: 'Joe'}; update(user); console.log(user); // Output: {name: "Ane"}
Example using array:
function update(arr) { arr.push('Ane'); } const user = ['Joe']; update(user); console.log(user); // Output: ["Joe", "Ane"]
If we try to overwrite the reference with a different object it will not affect the caller reference. Check the example below:
Example using new object:
function update(obj) { obj = {}; // new object reference } const user = {name: 'Joe'}; update(user); console.log(user); // Output: {name: "Joe"} // It did not change