DEV Community

uu
uu

Posted on

[JavaScript] Pass-by-value vs. Pass-by-reference

Before going forward with this article, I suggest you may read Immutable vs. Mutable

1.Passing by value of primitive value

pass-by-value means passing value/argument to function. The change to argument inside of function won't affect outside of function. But if you return function result, then that is another meaning.

let a = 10;
function change(x) {
    x = 20;
}
change(a);
console.log(a); //10 not change
Enter fullscreen mode Exit fullscreen mode
let a = 10;
function change(x) {
    x = 20;
    return x;
}
console.log(change(a));//20
Enter fullscreen mode Exit fullscreen mode

2.Passing by reference of object

pass-by-reference means passing address instead of argument to call a function. Changing the value inside the function affect its value ouside of function. Array and object pass-by-reference.

const person = {
    isStudent: true
};
function graduate(kid) {
    kid.isStudent = false;
}

graduate(person);
console.log(person.isStudent); // false; changed
Enter fullscreen mode Exit fullscreen mode

So you will see person is declared outside the function 'graduate'. When function is called, person 's value got mutated.

When you pass a reference to function, then function cannot change the reference to point to another object. An example as below:

const person = {
    isStudent: true
};
function graduate(kid) {
    kid = {
        isStudent: false
    };
}
graduate(person);
console.log(person.isStudent); // true; no change
Enter fullscreen mode Exit fullscreen mode

'kid' is another object, which is different from 'person' object.

Top comments (0)