JavaScript Hoisting

What is Hoisting?

In JavaScript, hoisting is the behavior of moving declarations to the top of a script or a function. This means that you can use variables and functions before they are declared in the code.

Hoisting with Variables :

Declarations of variables (but not assignments) are hoisted in JavaScript. This means that you can access a variable before it is declared in the code, but it will have a value of undefined. For example:

console.log(x);  // Output: undefined
var x = 5;

Here, the console.log statement is executed before the declaration of x, but because the declaration is hoisted to the top of the script, the value of x is undefined.

It's important to note that only declarations are hoisted, not assignments. In the following code, the value undefined will still be printed to the console because the declaration of x is hoisted, but the assignment of the value 5 is not.

Hoisting with Functions :

Function declarations are also hoisted in JavaScript. This means that you can call a function before it is defined in the code. For example

foo();  // Output: "Hello"

function foo() {
  console.log("Hello");
}

This is because the function declaration for foo is hoisted to the top of the script, so it can be called before it is defined.

Function expressions and arrow functions, on the other hand, are not hoisted. If you try to call a function expression or an arrow function before it is defined, you will get an error.

Hoisting with Objects :

Objects in JavaScript are a collection of key-value pairs. In JavaScript, object properties can be added or modified at any time, but object declarations are hoisted just like variables and functions.

console.log(obj.x);  // Output: undefined
var obj = { x: 5 };

Here, the console.log statement is executed before the declaration of obj, but because the declaration is hoisted to the top of the script, the value of obj is undefined. The assignment of the value { x: 5 } to obj remains in place.

It's important to note that only the declaration of the object is hoisted, not the properties or values that are assigned to it. In the following code, the value undefined will still be printed to the console because the declaration of obj is hoisted, but the properties and values of the object are not.