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!
In other OO languages, we can pass "pointers" or "references" to functionsnot nearly all of them. Java, for example, doesn't even have functions (not real ones, anyway - Java 8 has syntactic sugar over classes). Question is, why would you want to be able to pass by reference? What benefit does that have?