Hoisting in Javascript
In this article, we will cover hoisting in javascript, variable hoisting, function hoisting, as well as some examples of hoisting.
WHAT IS HOISTING
Hoisting is a behavior in JavaScript where variable and function declarations are “hoisted” to the top of their scope before code execution. This can result in confusing behavior, such as the ability to call variables and functions before you wrote them.
HOISTING IN VARIABLES
Variables are partially hoisted as shown below:
console.log(name)
var name="dev"
HOISTING IN FUNCTIONS Functions are fully hoisted as shown below:
console.log(display())
function display(){
console.log("hello")
}
The output will be:
hello
The output is hello because during the creation phase when JS Engine sees keyword function then it will remember its value and will allocate a memory for it.
SOME EXAMPLES TO CLEAR HOISTING CONCEPTS MORE ARE GIVEN BELOW:
EXAMPLE 1
var name="dev"
var show=function(){
console.log(name)
var name="rahul"
console.log(name)
}
show()
FIRST TRY YOURSELF THEN SEE THE OUTPUT BELOW
undefined
rahul
Did you get the same answer? If so, well done. Ok, so why did we first get undefined and then the name “rahul”? During the creation phase, JS Engine will see var keyword, and then it will give it a value as undefined to both show function and name keyword. And then During the execution phase, when it sees console.log() inside the function, it will remember that it is undefined and will print undefined. And then it sees that the name is equal to rahul and it will assign that value to memory. Afterward, it will console.log rahul as the name.
EXAMPLE 2
What will be the output:
display()
function display(){
console.log("hi")
}
function display(){
console.log("bye")
}
The output of the above code will be:
**bye**
The above output is “bye” because when we call a function there are two phases: creation and execution. During the creation phase, Hoisting occurs and it will see keyword function, and then first it sees function display then it will allocate memory for it and when it sees function display again then it will rewrite it in the memory. So now we have lost our first function display and hence the output is “bye”.
I HOPE THIS IS CLEAR.
DONT BE CONFUSED! We can simply avoid hoisting by using Let and const instead of var.
Using Let or const instead of var:
console.log(name)
let name="dev"
The above code error will come as you cannot display before initializing as it is in many programming languages.
Conclusion
Hoisting makes our code unpredictable and, as a programmer, we need to write good, readable, and predictable code. So we should avoid hoisting whenever we can. I hope that this post is able to give you a helpful overview of hoisting. Thanks for reading 😄