Hoisting: in detail

Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their scope, regardless of where they are declared in the code. This means that, even if a variable or function is declared in the middle or at the bottom of the code, it will still be accessible at the top of the code as if it were declared there.

For example, consider the following code:

console.log(num); // undefined
var num = 10;

In this code, num is declared using the var keyword. However, it is being accessed before it is declared. But, the code still runs without any errors. This is because of hoisting. Behind the scenes, the code is equivalent to the following:

var num;
console.log(num); // undefined
num = 10;

Here, we can see that the declaration of the num variable is hoisted to the top of the code, even though it was originally declared in the middle of the code.

Function declarations are also hoisted in the same way as variable declarations. Consider the following code:

sayHello(); // Hello!

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

Even though the sayHello function is declared after it is called, it still runs without any errors. This is because the function declaration is hoisted to the top of the code, making it accessible from anywhere in the code.

In conclusion, hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their scope, making them accessible from anywhere in the code. This behavior can be helpful in some cases, but it can also lead to unexpected results if you are not aware of it. So, it's important to keep hoisting in mind when writing JavaScript code.

Last updated