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!