R
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.
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);}
Hope you enjoyed this article! 🙂. If this article helped you please follow me on github and linkedIn for more such articles and other updates.
If you have any queries please write them below.