Wild Widow Wild Widow - 6 months ago 14
Javascript Question

value of javascript object not changing (pass by reference)

function outerFunction(x){
return function(y){
x=x+1;
console.log(x+y);
}
}
var myVal = new Number(2); //myVal is an object
console.log(myVal); //prints Number{[[PrimitiveValue]]: 2}

var innerFunction = outerFunction(myVal); //I'm passing myVal obj
innerFunction(10) //13
innerFunction(10) //14
innerFunction(10) //15

console.log(myVal); //prints Number{[[PrimitiveValue]]: 2} instead of 5?


I expected the last
console.log
to print
Number{[[PrimitiveValue]]: 5}
, since I passed
myVal object
to the
outerFunction
and in JS objects are passed by reference, why it didn't print 5?

Answer

Simple explanation using console.log (do check what javascript prints in console in this case):

function outerFunction(x){

    return function(y){

        console.log("type of x", typeof x); 
        console.log("value x:",x);
        console.log("value y:",y);

        x=x+1;
        console.log(x+y);
    }

}


var myVal = new Number(2); //myVal is an object
console.log(myVal); //prints Number{[[PrimitiveValue]]: 2}

var innerFunction  = outerFunction(myVal); //I'm passing myVal obj
innerFunction(10)   //13
innerFunction(10)   //14
innerFunction(10)   //15

console.log("type of myval",typeof myVal);

console.log(myVal);  //prints Number{[[PrimitiveValue]]: 2} instead of 5?// 

Here what is happening in your code.

==> Firstly you cannot add two objects in javascript using the + operator. So javascript converts it to a Number or a String (in this case a number as you are passing a number itself, which is a primitive type)

==> The inner function that you are returning has an outer reference of X from the outer function. (because of closures)

==> Each time you increment X, the value of x in the scope of outer function changes but it has now no effect on the global "myVal" variable(type object) as javascript considers the local X as primitive type (explained in the first point, which are passed by value and not by reference)

==> So the global value remains the same and X keeps changing which is accessed by inner function, that is why you see 13,14,15 as answers

Hope it helps