{ Hoisting. }

Objectives

By the end of this chapter, you should be able to:

  • Explain where a variable name gets defined in your code
  • Describe how hoisting affects function expressions vs function declarations

Hoisting

From MDN:

Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. When we used to use the var keyword, it meant that a variable could appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code. When we use the let and const keyword, we simply can not access a variable before it is declared. You will encounter hoisting when you compare function declarations and function expressions.

Hoisting In Function Declarations vs Function Expressions

So how does this work with function declarations vs function expressions?

Function declarations are fully defined before the code is run. So in the following example, we can call the sayHi function above the lines that define the sayHi function:

sayHi("Matt"); // "Hello Matt"

function sayHi(name){
    return "Hello " + name;
}

However, function expressions act differently. In the following example, there is an error because we are trying to invoke a function called sayHi but at that point in the code sayHi is not equal to a function. In fact, sayHi exists in memory but we can not access it and JavaScript will throw an error.

sayHi("Matt"); // Throws an error!

let sayHi = function(name){
    return "Hello " + name;
}

This is why we recommend that for now, you just use function declarations where you do not need to use the let or const keyword.

You can read more about hoisting here.

When you're ready, move on to Functions Exercises

Continue

Creative Commons License