Quirks With Javascript Scope and Hoisting

Whilst drowning myself in JavaScript today, I learnt a couple of things.

First was that there’s such a technique as “hoisting“. I’ve taken for granted that defining a function anywhere in my code (whilst in scope) will be available for use. Even if I’m calling a function before it’s actually been declared (converse to what you’d consider to be procedural).

That’s thanks to hoisting. Declarations of functions get bumped up to the top of the scope. The same goes to variables declared with the var construct.

Here’s a quick piece of code to describe how it works. This code will throw a ReferenceError when you put it through Firebug.

However, this is perfectly fine. (Will return ‘NaN’, which is expected. But no fundamental error.)

That’s because the varing gets thrown – hoisted – to the top of the script, along with any function declarations.

It’s important to remember this when you’re dealing with scope, and relying on JavaScript’s fairly lax approach to keeping scope.

You’ll see that returns “10”. A little more devils advocate gives us this.

This gives us “10, 5, 5”, which means that there’s been no scope restrictions coming into play here. Even inside the function, i has remained in global scope.

Before learning about hoisting, I would have expected the following code to give the same result.

Instead though, we get “undefined, 5, 10”. Using the var construct kick starts the scope restrictions right from the start of the function, not just after the line the variable gets declared on.

Bearing this in mind, for readability’s sake it makes sense to have all your variable declarations right at the top of the scope it’ll apply to. Otherwise you might fall into the trap of thinking a variable is still global, despite it being given function-scope in the last few lines.

You can also read Ben Cherry’s take on scope and hoisting.

One thought on “Quirks With Javascript Scope and Hoisting”

Leave a Reply

Your email address will not be published.