0

I've looked around a little bit, and I haven't found a clear answer as to why when this proceeding code is ran, it returns myInt as 0. I've read posts about how the variable is only changed inside the function, but from my perspective, I don't see any reason why myInt cannot be changed. For refrence, this is in Javascript.

var myInt = 0;

function changeVar(x) {
    x += 1;
}
changeVar(myInt);
console.log(myInt);
  • 1
    Javascript *always* passes variables to functions by value, except for arrays and objects. If you pass an object to a function, the "value" is really a reference to that object, so the function can modify that object's properties *but not cause the variable outside the function to point to some other object*. – Shekhar Chikara Oct 11 '17 at 03:36
  • 1
    Possible duplicate of [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Shekhar Chikara Oct 11 '17 at 03:37

2 Answers2

0

The reason myInt is not changing is that x has local scope (anything you do to x only affects the value of x inside of changeVar).

Here's how you could change myInt from changeVar():

var myInt = 0;

function changeVar() {
    myInt += 1;
}
changeVar();
console.log(myInt);

If you want to change a variable by passing it as an argument, you should pass an object instead:

var myObject1 = {value: 0}
var myObject2 = {value: 10}
function changeVar(x) {
    x['value'] += 1;
}
console.log(myObject1['value']);
console.log(myObject2['value']);

changeVar(myObject1);

console.log(myObject1['value']);
console.log(myObject2['value']);
N. Kern
  • 401
  • 2
  • 7
0

I will expand on the example given by @N.Kern - here is a better example of how to change the initial variable passed in the function:

var myInt = 0;

function changeVar(x) {
    return x += 1;
}
var y = changeVar(myInt);
console.log(y);

Now, the reason for this is offered by @Shekhar Chikara in the comment. Essentially, the value you're passing to the function is modified within the local scope of the function, but it's not actually assigned back (or saved in memory) to the globally declared variable. So when you log the original global variable, you get the unchanged value back. Thus, you want to simply save your functions' returned value to it's own variable.

This will get you started on researching more.

Hope this helps.

aleksandar
  • 186
  • 12