Hoisting

Hoisting is the behavior of moving the variables or function declarations to the top of their respective environments during creation phase.

Variables are partially hoisted and functions are fully hoisted.

Hoisting

console.log("What is hoisting?");
console.log(name);
console.log(hoisting());
var name = "Kai";
function hoisting() {
 console.log("It is defined");
}

// Result
What is hoisting?
undefined
It is defined
  • var variable is partially hoisted.
  • hoisting() function is fully hoisted.

During creation phase in JavaScript engine is going to look through the code and it sees two thing either var, function keywords, and it is going to allocate memory for variables and functions. Thus, the JavaScript engine when an execution phase knows that name is a variable which is not declared when it is called. So, it gives us undefined.

However, const, let keywords for JavaScript do not get hoisted.

In most languages where there is not hoisting. with hoisting, the JavaScript engine allocate some memory for us.

More examples

Function expression with var hoisting

console.log(hoisting())

var hoisting = function(){
 console.log("It is defined");
}
TypeError: hoisting is not a function
  • why? This is Error undefined is not a function.
console.log(hoisting)

var hoisting = function(){
 console.log("It is defined");
}
undefined

Same function name with hoisting

a()
function a(){
 console.log("1");
}
function a(){
 console.log("2");
}
2

During hoisting, first function a() is put in memory and replace the function a() in memory to next function a().

Hoisting happens in every execution context

var favoriteFood = "grapes";
var foodThoughts = function(){
  console.log("original: " + favoriteFood);
  var favoriteFood = "Sushi";
  console.log("new: " + favoriteFood);
}
foodThoughts()
original: undefined
new: Sushi

This is confusing. you should avoid hoisting by using const and let keywords.

Leave a Reply

Your email address will not be published.

ANOTE.DEV