Learn what is hoisting in Javascript | Javascript Interview Question.
Hoisting is a phenomena by which we can access variables and functions even before we have declared them without running into any error. Let's see the above statement in practice with the below example where we are trying to console variable "a" before it is declared.
We can see that the debugger is on the very first line of the code and none of the code has been executed yet but in the Global scope at the bottom we can see variable "a" is initialised to undefined and function "addNumbers" has the entire function definition assigned to it.
Output after running the code without any errors
# So why didn't we run into any errors here?
- A execution context was created for this code before the execution starts.
- The first step in an execution context is to allocate memory to each and every variable and function.
- During this assignment of memory it assigns each variable with a special keyword i.e. "undefined" and the functions declared using "Function Declaration" fashion with the entire function copy.
# Will a function work the same way as above if we declare the function using "function expression"?
No, it won't work as the function will be treated as a variable hence it will be assigned "undefined" during memeory allocation step.
# Will hoisting work the same way if we declare variables with "const" and "let"?
Hoisting doesn't work with const and let. They are also hoisted but are never hoisted with a default value like it happens in case of var and functions. Hence, we will run into a ReferenceError.
Using let
console.log(a); let a = 10;
Using const
addNumbers(2, 4); const addNumbers = function (a, b) { console.log(a + b); };