Consider this code:
Many developers would expect undefined
, since the var a
statement comes after the a = 2
, and it would seem natural to assume that the variable is re-defined, and thus assigned the default . However, the output will be 2
.
You might be tempted to assume that, since the previous snippet exhibited some less-than-top-down looking behavior, perhaps in this snippet, 2
will also be printed. Others may think that since the a
variable is used before it is declared, this must result in a ReferenceError
being thrown.
So, what’s going on here? It would appear we have a chicken-and-the-egg question. Which comes first, the declaration (“egg”), or the assignment (“chicken”)?