Is JavaScript a pass-by-reference or pass-by-value language?

JavascriptFront End TechnologyObject Oriented Programming

Javascript is a pass by value language. But for objects, the value is their reference. So for example, if you pass an int to a function as parameter and increment its value in the function, its value will not be updated in the caller's context −

Example

let i = 0;
function increment(x) {
   x = x + 1
   console.log(x)
}
increment(i)
console.log(i)

Output

1
0

When you pass an object and update that object's reference in the function's context, that won't affect the object. But if you mutate the object's internals, that'll reflect in the object.

Example

let obj = {'foo': 'bar'};
function updateRef(x) {
   // x's local ref gets updates, doesn't affect obj
   x = {}
}
function addHelloWorld(y) {
   // Add new prop to object referenced by y
   y['hello'] = 'world';
}
console.log(obj)
updateRef(obj)
console.log(obj)
addHelloWorld(obj)
console.log(obj)

Output

{ foo: 'bar' }
{ foo: 'bar' }
{ foo: 'bar', hello: 'world' }

Note that the object reference change did not affect the object. The local variable x was reassigned. In second function however, y was referencing the obj object and mutated the internal state of that object. This caused the change in the original object.

raja
Published on 16-Sep-2019 06:26:51
Advertisements