Learn what is hoisting in Javascript | Javascript Interview Question.

JavascriptRupali Yadav10 Oct 20222 min read

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.

hoisting in javascript | webexpe.com

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

hoisting in javascript | Rupali yadav | webexpe.com

# So why didn't we run into any errors here?

  1. A execution context was created for this code before the execution starts.
  2. The first step in an execution context is to allocate memory to each and every variable and function.
  3. 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.

hoisting in javascript | Rupali yadav | webexpe.com

# 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;
hoisting in javascript | Rupali yadav | webexpe.com

Using const

addNumbers(2, 4); const addNumbers = function (a, b) { console.log(a + b); };
hoisting in javascript | Rupali yadav | webexpe.com
hoisting
undefined
javaScript

Share on:

Support Us:

Buy Me A Coffee