Block Scope and Hoisting – An Exercise in Rubber Ducking

This is a follow up to  ‘Intro to Scope’, previously posted here at CrookedCode.  It’s part of our rubber ducking series, where we’re attempting to work through some of the more difficult parts of JavaScript using Kyle Simpson’s book series, You Don’t Know JS, as a guide.

If you want to know more about the project, check out this post.  If you’re thinking to yourself “Where does this guy get off thinking he can explain this stuff better than Kyle Simpson?”, check out the disclaimer here. Otherwise, read on…

As the title suggests, this post will cover block scope versus function scope, particularly as they pertains to varlet and const. I’d like to start with the concept of hoisting, however, as I think it’ll help understand the rest of the article.

WTF is Hoisting?  (And Do I need a boat to do it?)

Consider the following:

The question here is will “Will this get logged?” actually get logged to the console even though hoisted is declared after it  A) has a value assigned to it and B) gets logged.

The answer is yes, “Will this get logged?” is logged to the console.

You’ve also probably seen examples of functions getting invoked before they’re even declared.  Have you wondered why that works too…

Something like:

The above snippet will log ‘Henry’ to the console.

Both of the above examples work because of hoisting.  As we mentioned in the previous article, JavaScript is a compiled language.  Part of the compilation step is finding all the declarations (variables and functions) and associate them with the appropriate scope.

This part actually occurs first, before the code is executed.  Therefore any function or variable declared in a given scope will be available throughout that scope.

In the first example above, var hoisted would have been ‘hoisted’ to the top of scope within the hoist() function.  So when the JS engine comes across hoisted = a and searches for a variable called hoisted in the lexical scope within the hoist() function, it’ll find it!

One more note on hoisting…

Don’t confuse declaring a variable with assigning a value to a variable, even if that happens in the same line of code.

var name = 'Henry'; is seen as two statements by the JS engine, var name; and name = 'Henry';. The declaration is hoisted, the assignment is not…

If you think this is just semantics, consider the following:

Someone with a tenuous grasp on scope might look at this snippet of code and think there are a couple possibilities…

“That’ll probably be a ReferenceError because a is declared after it’s logged..”

Nope…

or if they’ve heard of hoisting….

“Maybe it’ll print ‘Henry’ to the console because a is hoisted within the printYourDogsName function”

Nope again…

The actual answer is that the snippet logs undefined.  If you think back to the last article, undefined (as opposed to ReferenceError) means that the JS engine found the variable a (because it was hoisted), but a was undefined (because the a = name assignment didn’t happen until after console.log(a).

Ok, enough about hoisting… I think that should give us a pretty good grasp on how things work.  For more detail please refer to YDKJS.

The Complexity of Scope

I hope my previous article, along with what’s covered here, has given you a pretty good understanding of lexical scope and how it works in JavaScript.  So why did Kyle Simpson feel the need to devote an entire book to scope and closures?

You know the old saying ‘You don’t know what you don’t know…”?  Well, there are several special circumstances that are covered in ‘Scope and Closures’ that I won’t be addressing here at Crooked Code of which you should be aware.

One such concept is using scope to hide access to variables.  I plan to touch upon some of this in a future article on Modules, but in the meantime, YDKJS covers it here.

You can also read about the specifics of scope as it pertains to function expressions, including Immediately Invoked Function Expressions or IIFEs, here.

The final topic you should be aware of that I won’t be covering in this article is closure.  Simpson devotes an entire chapter to closure and I highly recommend reading it.

I’ve read it a couple times and my pulse still quickens a bit when someone mentions closure (I’ll be writing a rubber ducking article here on closure in the near future to solidify the concept in my own head).

Now on to Block Scope

We’ve discussed previously that JavaScript uses functions to define scope.

This was, for the most part, entirely true until ES6.  Among the changes in ES6 were the keywords let and const, which provide us ways to declare variables with block scope.

The only difference between the two is const declares a constant, which can’t be changed once assigned a value.

Before we get into what block scope is, there’s a key note to remember when dealing with let and const.  They are NOT hoisted within their block of scope.  This means that you must declare them before you use them or it will result in a ReferenceError.

Now, what’s block scope?  Simpson tells us a block is commonly a {...} pair. So think for loops, if statements, etc..  You can even create your own block of scope by enclosing code in curly brackets.

Block scope can be useful in several key ways…  Consider the following:

In this example, as I’m sure you can figure out by now, 10 (not 42) would get logged to the console.  This is because i would be hoisted to the scope within the redundantI function.  So when the engine comes across the var i = 0 statement in the for loop, it will already see the i variable and use that one.  Now consider:

This snippet would actually result in 42 getting logged.  Why? Because let created a new i variable for use ONLY in the for loop!

I realize this example is pretty idiotic and you’re probably thinking to yourself “This guy is effing nuts… I’d never make that mistake in my code…”.

I know you wouldn’t make a mistake like that, but think about functions that are 100+ lines of code with a couple additional functions nested within.

If you’re using a variable for the sole purpose of controlling the for loop, wouldn’t you prefer to keep it out of the overall scope? Wouldn’t it be nice if you could use the variable in the loop, then have it go away?  let enables that…

Simpson also discussed using block scope to enable garbage collecting when you’re handling large amounts of data.  It’s a pretty interesting concept and can be read in the garbage collection section of Chapter 3.

The final point to mention regarding the use of let concerns its use in loops.  Simpson points out that, not only does let bind the variable to the body of the for loop, but it re-binds the variable to each iteration of the loop.

This may seem trivial, but when you consider closure it can be a very useful behavior if you understand it enough to use it properly.  I’ll cover this in more detail in my article on closure, but you can read about it now in the YDKJS section called ‘Block Scoping Revisited’.

That’s it for now…  If anyone’s still reading, thanks for taking the time.  I hope I was able to straighten out the code for you.

-Jeremy

Leave a Reply

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