JavaScript Scoping and Hoisting

Adequately Good – JavaScript Scoping and Hoisting – by Ben Cherry.

I was not aware at all of “hoisting” in JavaScript, which causes your variable declarations (but not initializations) to be rearranged to the top of your function scope by the interpreter. Function definitions, however, are hoisted along with the function body.

Implications:

  • potentially unexpected behavior if you expect to conditionally declare a variable at runtime
  • before runtime, all of your variable definitions will be shuffled to the top of the function body anyway. The only reason to declare-at-time-of-use is then readability (vs. any performance gains), with the downside that you can’t easily see your scope.
  • it matters how you declare your functions. var foo = function () { }; will hoist just the variable declaration, but not the function definition. function foo() { }; will hoist both the definition and the function body.

For me, this is another strong reason to predeclare all variables at the top of your function. It’s going to happen anyway.

Leave a comment

Your email address will not be published. Required fields are marked *