Today’s video quick tip comes in response to a question on Twitter, concerning JavaScript “hoisting.” What is it? How does it work? What do you need to know about it? All of that will be covered in this beginner-focused fundamentals lesson.



Full Screencast

Hoisting Explained

Consider the following code:

Okay, of course the alert will display “my value.” That’s obvious; however, stick with me. Let’s next create an immediate function, which alerts the same value.

All right, all right. Still obvious, I know. Now, let’s throw a wrench into the mix, and create a local variable within this anonymous function of the same name.

Huh? Why is the alert now displaying undefined ? Even though we’ve declared a new variable, it’s still below the alert; so it shouldn’t have an effect, right? Wrong.

Variable Declarations are Hoisted

Within its current scope, regardless of where a variable is declared, it will be, behind the scenes, hoisted to the top. However, only the declaration will be hoisted. If the variable is also initialized , the current value, at the top of the scope, will initially be set to undefined .

Okay, let’s decipher the difference between the terms, declaration and initialization . Assume the following line: var joe = 'plumber';

Declaration

Initialization

Now that we understand the terminology, we can more easily comprehend what’s happening under the hood. Consider the following bogus function.

Declare all variables at the top.

Note that what’s exemplified above is considered to be bad practice. Nonetheless, behind the scenes, all of those variable declarations — regardless of where they occur in the function scope — will be hoisted to the top, like so:

Aha Moment

If we now return to the original confusing undefined piece of code, from above: