Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Does it actually allow it? I thought the declaration is just hoisted to the top of the scope?


I just recently read about this in the You Don't Know JS series of books:

"We can be tempted to look at var a = 2; as one statement, but the JavaScript Engine does not see it that way. It sees var a and a = 2 as two separate statements, the first one a compiler-phase task, and the second one an execution-phase task.

What this leads to is that all declarations in a scope, regardless of where they appear, are processed first before the code itself is executed. You can visualize this as declarations (variables and functions) being "moved" to the top of their respective scopes, which we call "hoisting".

Declarations themselves are hoisted, but assignments, even assignments of function expressions, are not hoisted.

Be careful about duplicate declarations, especially mixed between normal var declarations and function declarations -- peril awaits if you do!"

https://github.com/getify/You-Dont-Know-JS/blob/master/scope...


It is hoisted at runtime. There is no compile/transpile step that physically moves the declaration to the top, so syntactically the declaration can be after variable usage.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: