What is Hoisting in JavaScript?
Hoisting is a term used to describe the behaviour of variable declarations in JavaScript. In JavaScript, variable declarations are physically moved to the top of their containing scope by the interpreter, but the assignments are left in place.
This means that, in JavaScript, it is possible to use a variable before it has been declared.
How Does Hoisting Work?
In JavaScript, there are two types of scope: global scope and local scope.
A variable declared outside of any function is in the global scope and can be accessed from anywhere in the code. A variable declared within a function is in the local scope and can only be accessed within that function.
When the JavaScript interpreter encounters a variable declaration, it moves the declaration to the top of the current scope. This is why it is called "hoisting".
Examples of Hoisting
x = 5;
elem = document.getElementById("demo");
elem.innerHTML = x;
var x;
In the above code, the declaration of the variable x
is hoisted to the top of the global scope, so it is accessible throughout the code. However, the assignment x = 5
is not hoisted, so it stays in place.
function example() {
y = 10;
var z = 15;
elem = document.getElementById("demo");
elem.innerHTML = "y = " + y + ", z = " + z;
}
example();
In this example, the declaration of the variable z
is hoisted to the top of the example
function, but the assignment z = 15
is not. The assignment y = 10
is also not hoisted, so it stays in place.
Why is Hoisting Important?
Hoisting is an important concept to understand in JavaScript because it can affect the order in which code is executed.
For example, consider the following code:
Copy codex = 5;
elem = document.getElementById("demo");
elem.innerHTML = x;
var x;
At first glance, it may seem that the value of x
is being displayed before it is assigned a value. However, due to hoisting, the declaration of the variable x
is moved to the top of the global scope, so it is accessible throughout the code.
Hoisting and Function Expressions
Function expressions, on the other hand, are not hoisted in JavaScript. This means that it is not possible to use a function expression before it is declared in the code.
For example:
x(); // Uncaught TypeError: x is not a function
var x = function() {
console.log("This function has not been hoisted.");
};
In this example, the function x
is called before it is declared, but since it is a function expression and not a function declaration, it is not hoisted and the code throws an error.
Conclusion
In conclusion, hoisting is a behaviour in JavaScript in which variable declarations and function declarations are physically moved to the top of their containing scope by the interpreter. This can affect the order in which code is executed and it is important to understand how hoisting works to write correct and predictable JavaScript code.