Ben Cherry's excellent article explains hoisting in JavaScript adequately. My problem, however, is that I cannot conceive a use case for this notorious perpetrator of confusion. Please explain if there is a design pattern that actually takes advantage of this language feature.
Secondly, is scope hoisting unique to JavaScript?
UPDATE --- I'm adding a bounty for an answer that satisfies my curiosity: Which design pattern(s) actually take advantage of JavaScript's hoisting behavior? I understand why JavaScript supports hoisting, but I want to know how I can take advantage of this feature.
JavaScript does not have block scope (let's forget about
let
for now) and thus any variable declaration is declaring for the entire function, of which JavaScript does have scope.If you think about it that way, JavaScript hoisting may make more sense.
If you remember about hoisting, it shouldn't be a source of bugs and confusion. It's simply one of those quirks you must understand and remember.
I'm not sure if hoisting is limited to JavaScript. I've never heard of it elsewhere, but that doesn't necessarily mean it doesn't exist in other languages.
Here's a real use case (albeit reduced to pseudo-code) for you, from someone who would actually want to use the benefits of hoisting in the wild.
I recently wrote this script for handling simple form validation and submission. As far as possible, each function declaration invokes the following. This has 2 chief benefits for readability:
"hoisting" is not part of the ECMAScript Standard, but it does say that variable inside a function are declared at the begin of the function regardless of where in the function it is place in the code.
Example
Internally Javascript would declare myvar before the alert, show the alert, then it would assign myvar to 'local value'.
So Javascript would interpet that code as:
That is why "Java the Good parts" has a guideline that say you should declare variable at the top of your function.
Source: http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/
"Please explain if there is a design pattern that actually takes advantage of this language feature." "hoisting" is not a feature but rather a consequence how the Javascript interpreter structure the code since the language uses function-scoping.
"Which design pattern(s) actually take advantage of JavaScript's hoisting behavior? " Answer: None.