Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - primitive vs reference types [duplicate]

In the below code we are passing an object. So, according to javascript we are passing a reference and manipulating.

var a = new Number(10);
x(a);
alert(a);

function x(n) {
n = n + 2;
}

But 10 is alerted instead of 12. Why?

like image 340
sarthak sharma Avatar asked Dec 07 '14 08:12

sarthak sharma


2 Answers

n is local to x and first it is set to the same reference as global a. The right hand side n + 2 is then evaluated to be a number (primitive). The left hand side of the assignment, n, is never evaluated, it is just an identifier there. So our local variable is now set to the primitive value of the right hand side. The value referenced by a is never actually modified. See

var a = new Number(10);
x(a);
alert(a);  // 10

function x(n) {
  alert(typeof n);  // object
  n = n + 2;
  alert(typeof n);  // number
}
like image 193
g.kertesz Avatar answered Oct 11 '22 14:10

g.kertesz


When you compute

n + 2

this results in a new "native number" even if n is indeed a Number object instance.

Assigning to n then just changes what the local variable n is referencing and doesn't change the Number object instance. You can see that with

n = new Number(10);
console.log(typeof n);     // ---> "object"
console.log(n + 2);        // ---> 12
console.log(typeof (n+2)); // ---> "number"
n = n + 2;
console.log(typeof n);     // ---> "number"

In Javascript (or Python or Lisp) there's no way to pass the "address" of a variable so that the called function mutates it. The only thing you can do is passing a setter function... for example:

function foo(setter) {
    setter(42);
}

funciton bar() {
    var x = 12;
    foo(function(newx){x = newx;});
    console.log(x); // ---> 42
}
like image 26
6502 Avatar answered Oct 11 '22 13:10

6502