Is there thing like pass by value pass by reference in JavaScript?

Other answers to this question are correct – all variables are passed by value in JavaScript, and sometimes that value points to an object.

When a programming language supports passing by reference, it’s possible to change where the variable points from inside a function. This is never possible in JavaScript.

For example, consider this code which attempts to reassign the passed variable to a new value:

function changeCaller( x ) {
    x = "bar";  // Ha ha!
}

function testChangeCaller() {

    var x = "foo";

    changeCaller(x);

    alert(x); // still "foo"

}

testChangeCaller();

Attempts to point variables at new objects fails in the same way the above example fails to reassign a primitive string:

function changeCaller( x ) {
    x = new Object(); // no longer pointing to the same object
    x.a = "bar";
}

function testChangeCaller() {

    var x = new Object();
    x.a = "foo";

    changeCaller(x);

    alert(x.a); // still "foo"

}

testChangeCaller();

The feature which leads people to believe they’re dealing with a pass-by-reference scenario is when modifying objects. You can make changes to an object or array, because the local variable points to the same object:

function changeCaller( x ) {
    x.a = "bar";
}

function testChangeCaller() {

    var x = new Object();
    x.a = "foo";

    changeCaller(x);

    alert(x.a); // now "bar", since changeCaller worked on the same object

}

testChangeCaller();

Hope this helps!

Leave a Comment