Understanding Hoisting in JavaScript

Understanding Hoisting in JavaScript

Have you ever heard of hoisting in JavaScript and wondered what it meant? Or maybe you’re familiar with the term, but don’t know exactly what it does. In this article, we’ll take a closer look at hoisting, and how it works in JavaScript.

In JavaScript, hoisting refers to the behavior of moving variable and function declarations to the top of the current scope. This happens during the compilation phase, before the code is executed. The purpose of hoisting is to allow code to use a variable or function before it has been declared.

Let’s consider an example of hoisting. Suppose we have the following code:

console.log(one);
var one = 2;

What do you think this code does? During the hoisting phase, one is assigned to undefined. When the JavaScript engine sees the second line, it ignores it because it already has a declaration for one. Therefore, when we run console.log(one), it prints undefined.

Now let’s look at another example:

justAFunction();

function justAFunction() {
console.log('Hello mate!!!');
}

function justAFunction() {
console.log('Ba Bye!!!');
}

What do you think happens when we run this code? During the hoisting phase, both functions justAFunction are fully hoisted because they are function declarations. However, because we are defining two functions with the same name, the second function overwrites the first one. As a result, when we call justAFunction(), it prints Ba Bye!!!.

Hoisting also occurs when we create a new execution context by calling a function. Consider the following example:

var favoriteAirplane = "777 - Boeing";

function airplaneThoughts() {

console.log("Original favorite Airplane:", favoriteAirplane);
var favoriteAirplane = "A380 - Airbus";
console.log("New favorite Airplane:", favoriteAirplane);

}

airplaneThoughts();

What do you think this code does? During the hoisting phase, favoriteAirplane is assigned to undefined. When we call the airplaneThoughts function, a new execution context is created. During the creation phase of this new context, the favoriteAirplane variable is hoisted to the top, but it is not yet assigned a value. Therefore, when we log the value of favoriteAirplane on the first line of airplaneThoughts(), it prints undefined. Later, when we assign favoriteAirplane to "777 — Boeing", it logs the new value.

In conclusion, hoisting is an important concept in JavaScript that helps explain the behavior of variable and function declarations. Understanding hoisting will help you write more efficient and effective code.