How come the following code is giving me a 0 instead of a 1? I want my function to change a variable declared outside the function but I do not want to specify the variable in the function declaration.
that = 0;
function go(input) {
input++;
}
go(that);
console.log(that);
That's because you are passing the variable by value, not by reference.
In javascript, all variables are passed by value, except objects, which are passed by reference (well, in fact they are passed by value too but they are a reference, see below).
And you can't change that behaviour.
Edit: If you don't know what passing by value/reference means, you should read a tutorial. But here you have some examples:
Variable passed by value
Variable passed by (value but used as a) reference
In your case
You can do
Make your variable a property of an object (in your case, since it's a global variable, use
window
) and pass the object (reference), so you can alter itUse a return value
Note that you can't do
Convert your variable into an object
That's because objects are passed by value too, but they are a reference. That means that inside the function you can change the properties of the outer object (because it's a reference) but you can't change the entire object, because it's passed by value.
See examples here: https://stackoverflow.com/a/3638034/1529630
This has to do with pointers, scope, passing variables by reference, and all that jazz.
If you really want to do this, you can pass an object in Javascript like this:
All we've done is made that an object which is by definition passed as a reference in Javascript. Then we just make sure we properly modify the object's attributes.
Your code
Instead do this
As answered by Oriol, it doesn't work because the variable is passed by value, so you're not changing the "that" variable. A workaround would be to pass the variable name :