Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing primitive variables by refence javascript [duplicate]

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!

like image 521
qxu21 Avatar asked Sep 19 '16 21:09

qxu21


1 Answers

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.

like image 164
traktor Avatar answered Sep 28 '22 02:09

traktor