1

I come from Java and find this language similar to Java in many places. recently I went across a program where I referenced variable before the variable declaration in the if-else block, why is this not throwing a syntax error?

function add(x, y, toDbl) {
    result = 0;

    if (toDbl) 
      var result = (x + y) * 2;
    else
      var result = (x + y);

    return result;
}
  • Better to use `const` or `let` instead - they're not (exactly) hoisted, referencing them while they're in the TDZ will throw a SyntaxError – CertainPerformance May 06 '19 at 07:09
  • When you try to assign a value to a non-declared variable, you create (and initialize) a global variable. Even if you do this inside a function. Later in your function, you declare a variable with the var keyword, making it a variable that is scoped to that function - therefore those are 2 different variables. I hope this makes sense. – ondrejm May 06 '19 at 11:05

0 Answers0