0

I was looking at this javascript code:

var a = {i: 0};
var b = 0;

function change(a, b) {
  a.i++;
  b++;
}
change(a, b);

console.log(a, b);

You would expect to be logged: {i:1} 1 . It actually returns: {i:1} 0? Why is b=0 and not b=1?

Eddie
  • 26,593
  • 6
  • 36
  • 58
bier hier
  • 20,970
  • 42
  • 97
  • 166

2 Answers2

4

Because b is a parameter inside change - inside change, b refers to the local variable, and when the local variable is reassigned, that has no effect on the b outside.

Either always refer to b as a global variable:

var a = {i: 0};
var b = 0;

function change(a) {
  a.i++;
  b++;
}
change(a);

console.log(a, b);

Or return b from change, and assign the outer b to the result of change:

var a = {i: 0};
var b = 0;

function change(a, b) {
  a.i++;
  b++;
  return b;
}
b = change(a, b);

console.log(a, b);

(if you need to return and reassign multiple variables, return an object or array:

var a = {i: 0};
var b = 0;
var c = 0;

function change(a, b, c) {
  a.i++;
  b++;
  c++;
  return { b, c };
}
({b, c} = change(a, b, c));

console.log(a, b, c);

)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

You're shadowing your variable a in your function header.

function change() {
    a.i++;
    b++;
  }

will work.

Moritz Roessler
  • 8,542
  • 26
  • 51