HappyCoding HappyCoding - 3 months ago 5
Javascript Question

Why had code inside if (false) statement been read?

What I want to achieve: if something went wrong (

if (false)
), re-define object
A
. Then, create new variable
a
to assign to
A
.



class A {

}
class B {

}
class C {
constructor() {
if (false) {
console.log('hit'); // never hit to
var A = B
}
var a = A;
console.log(a) // undefined
}
}
var c = new C();





I'm not sure the line
var A = B
was executed, but if I remove the
if
statement,
console.log(a)
would print:

class A {

}


My question: Why am I getting
undefined
in the line
console.log(a)
?

Answer

All var statements in a function, regardless of where they appear, are treated as if they appeared at the top of the function. Thus, your function is interpreted exactly as if it were written:

class C {
  constructor() {
    var a, A;
    if (false) {
      console.log('hit'); // never hit to
      A = B
    }
    a = A; 
    console.log(a) // undefined
  }
}

Thus because the variables a and A appear somewhere in the constructor function in var declarations, they're declared throughout the entire function. The initializations of the declared variables are evaluated where the var declarations actually appear.

Comments