On our previous post, we looked at variable hoisting. In this post, we will take a look at function hoisting, which is part two of JavaScript Hoisting concept and part of our JavaScript basic concept series.
Let's start with a code example,
The above way of writing a method with a function
keyword is called a function declaration.
Function declarations are always hoisted by JavaScript in its existing scope. And you can see that the function foo()
is available before its declaration.
You can write a function in another way and its called function expression. With function expression, you declare an anonymous function and assign it to a variable. Let's see that with a code example.
Function expression on both ES5 and ES6 will not get hoisted. The variable declaration will get hoisted but without a function assignment. The interpretation of the above code by JavaScript will be,
ES6 Classes
The data type of an ES6 class is a Function. So, classes behave the same as function when it comes to hoisting. Class declarations are hoisted and Class expressions are not.
There is one extra rule with class declarations, you have to declare a class before you can use it. Let's take a look,
The fact that the error is "initialisation" error and that it is not a 'is not defined' error, proves that JavaScript can see its definition hence it is hoisted.
Same as function expression, class expressions are not hoisted.
Summary
- Function and ES6 Class declarations are hoisted.
- Function and ES6 Class expressions are not hoisted.
- ES6
let
andconst
hoist the same way asvar
does.