Hoisting is the process of moving variable and function declarations to the top of their scope before the code is executed. This means that we can use variables and functions before they are declared in the code. However, the value of the variable is not hoisted, only the declaration part is moved to the top.
Let's see a simple example of hoisting in JavaScript:
console.log(x); // undefined
var x = 5;
console.log(x); // 5
In the example above, we have two calls to the console.log function to print the value of the variable x. Before declaring the variable x, we called console.log(x) and the result was undefined. This happens because the variable x has been hoisted, but its value has not been assigned yet.
Then, we declare and assign the value 5 to the variable x. The second call of console.log(x) will print the value 5.
Hoisting also applies to function declarations and definitions in JavaScript. We can call a function before it is declared in the code.
hello(); // "Xin chà o!"
function hello() {
console.log("Xin chà o!");
}
In the example above, we call the hello() function before it is declared. This is because JavaScript has hoisted the hello() function to the top of its scope. When executed, the function will be called and print the string "Hello!".
Although hoisting applies to variable declarations with the var keyword, it does not apply to variables declared with let and const. This means that we cannot use let and const variables before they are declared.
console.log(x); // Lá»—i: Cannot access 'x' before initialization
let x = 5;
console.log(x); // 5
In the example above, when we try to call console.log(x) before the variable x is declared, JavaScript will throw an error "Cannot access 'x' before initialization". This happens because the let variable is not hoisted and cannot be used before it is declared.