What is hoisting in JavaScript?

Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their respective scopes (i.e., global or functional) before the code is executed. This means that, regardless of where a variable or function is declared in the code, it can be referenced or called before it is declared.

For example:

console.log(x); // logs "undefined"
var x = 10;

In this code, the var x declaration is “hoisted” to the top of the code, and undefined is logged because x has been declared but not yet assigned a value.

It’s important to note that hoisting applies only to declaration, not to assignment. So, for example, the following code will throw a ReferenceError:

console.log(x);
var x;
x = 10;

This is because, even though the declaration has been hoisted, the assignment has not and so x is not yet defined.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *