Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed. This means that you can use variables and functions in your code before they are declared in the source code, which might seem counterintuitive but is important to understand.
There are two main aspects of hoisting in JavaScript:
Variable Hoisting:
When you declare a variable using var, it is hoisted to the top of its containing function or global scope. However, only the declaration is hoisted, not the initialization. This means that the variable is accessible before its declaration in code but will have an initial value of undefined.
In the code above, x is hoisted to the top of the scope, so the console.log(x) statement doesn't throw an error. Still, x is undefined until it's assigned the value 10 later in the code.
It's important to note that the behavior of let and const is different. Variables declared with let and const are also hoisted to the top of their scope, but they are not initialized until the actual declaration in the code. This is known as the "temporal dead zone," and trying to access such variables before declaration results in a ReferenceError.
console.log(x); // undefined
var x = 10;
Function Hoisting: Function declarations are also hoisted to the top of their containing scope, including their entire definition, not just the name.
In the code above, the greet() function is called before its declaration, but it works as expected because the entire function, including its definition, is hoisted to the top.
greet(); // "Hello, world!"
function greet() {
console.log("Hello, world!");
}
<aside> 💡 class, let and const are non hoisting
</aside>