Share:

R

Rupali Yadav

in

javascript

Oct 10, 2022

What is hoisting in Javascript

#hoisting

#undefined

#javaScript

#webexpe

#webexpe.com

#rupali yadav

#rupali

# Hoisting in javascript

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?

  • 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.
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
Thanks for reading with us till here 🙂. If this article helped you please follow me on twitter, github and linkedIn for more such articles and other updates.
If you have any queries please write them below.

More from Author

Difference between pass by value and pass by reference in javascript
Difference between pass by value and pass by reference in javascript
How to use ref to style in react
How to use ref to style in react
Difference between a state and prop in react
Difference between a state and prop in react

Share:

Copyright © 2022 Web Expe

Privacy PolicyTerms and Conditions