Sebastian Fischer Sebastian Fischer - 2 months ago 8
Node.js Question

Passing primitive variables by refence javascript

I'm trying to pass primitive variables by reference.

var foo = 2;
function inc (arg) {
arg++
}
inc(foo) //won't increment foo


The above doesn't work because in JavaScript, primitives (like numbers) are passed by value, while objects are passed by reference. In order to pass primitives by reference, we need to declare them as objects:

var foo = new Number(2)
function inc (arg) {
arg++
}
inc(foo) //increments foo


This seems like a pretty hacky workaround, and probably hurts execution speed. In other OO languages, we can pass "pointers" or "references" to functions. Is there anything like this in JS? Thanks!

Answer

You can't pass primitives by reference in Javascript - and the example "workaround" does not work. Here's why:

var foo = new Number(2)  // line 1
function inc (arg) {     // line 2
    arg++                // line 3
}

Line 1 sets foo to a Number object wrapper with primitive value 2.

Line 2 defines a formal parameter arg which has its own storage location in function scope to hold a copy of the value of the argument.

Line 3 increments the actual parameter value (a copy of the Number object reference) where it is stored - in memmory allocated for arg, not foo. If you check the primitive value of foo after the call it is still 2.

In practice you can pass a reference to an object with a foo property that is incremented:

var obj = {}
obj.foo = 2
function incFoo (obj) {
    obj.foo++
}
incFoo()  // obj.foo now 3

Essentially there are no address pointers available in ECMA script to reference primitive values.

Comments