Skip to content
Advertisement

Why the initial value did not change?

Help please, why the initial value did not change? *For some reason if I remove clock “else” everything works fine.

    var value = 0;

    function f() {
        if (true) {
            value = 15;
        }
        else {
            var value = false;
        }
        console.log('changed value',value);
    }

    f();
    console.log('value ',value);

Advertisement

Answer

Due to hoisting, the var moves the declaration to the top of the function. So instead of value being the reference to the global, it is now scoped to your function. So your code actually looks like this:

var value = 0;

function f() {
  var value;
  if (true) {
    value = 15;
  } else {
    value = false;
  }
  console.log('changed value', value);
}

f();
console.log('value ', value);

To solve it, you need to get rid of the var inside your function.

var value = 0;

function f() {
  if (true) {
    value = 15;
  } else {
    value = false;
  }
  console.log('changed value', value);
}

f();
console.log('value ', value);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement