What is Hoisting ?
This means no matter where in the file the declaration was actually made, upon compiling it will be hoisted to the top. But hoisting is not carried out for every declaration, it is restricted to variables declared using keyword ‘var’ and functions declared using keyword ‘function’.
No matter where in the code a variable is declared, if it is declared using the keyword ‘var’ then post compilation it appears to the compiler as if that variable was declared at the top of its scope be it global or functional scope. But the same thing if tried with keywords ‘const’ and ‘let’ then the results will be different.
The above code snippet upon compiling will become below snippet:
A similar phenomenon happens when we use the ‘function’ keyword to declare our functions. The function signature gets hoisted to the top of the scope and if that function was called in the scope before it was defined it works perfectly. But the same thing if tried with function expression i.e. defining anonymous functions and storing their references in a const or let variable, it will throw an error “Cannot find [function name]”.
The below code works fine because the function is declared using the ‘function’ keyword and therefore it gets hoisting to the top.
But the code below throws an error “Cannot find [function name]”, because it’s a function expression and function expressions don’t fall under the scope of hoisting.
Hoisting is actually limited to variables declared using the keyword ‘var’ and functions declared using the keyword ‘function’.
Let’s understand this with an example:
- Defining > Calling > Declaring
- Calling > Defining > Declaring
To avoid hoisting and to make your code predictable, as of ES6 or ES2015 we have new ways of declaring variables which include ‘const’ and ‘let’ and we also have the beautiful arrow functions ()=> as well.
These new features are excluded from the scope of hoisting. So when you declare a variable using ‘const’ or ‘let’ or an arrow function do not expect it to be hoisted to the top, thus making your code more predictable and human readable.
Get In Touch
How Can We Help ?
We make your product happen. Our dynamic, robust and scalable solutions help you drive value at the greatest speed in the market