Hoisting is a behavior in JavaScript where variable declarations and function declarations are moved to the top of their respective scopes during the compilation phase before the code is executed.
This means that variables and functions can be accessed and used before they are formally declared, but only the declaration is hoisted, not the initialization or assignment.
For example, consider the following code snippet:
console.log(x);
var x = 5;
Normally, this code would throw a ReferenceError because x
is not defined before it is used. However, because of hoisting, the code is actually interpreted like this:
var x;
console.log(x);
x = 5;
Function declarations are also hoisted to the top of their scope.
foo();
function foo() {
console.log("Hello, world!");
}
Hoisting in JavaScript example
Simple example code.
greet();
function greet() {
console.log('Hi, there.');
}
The above code will work as expected due to hoisting. During the compilation phase, the function declaration of greet()
is moved to the top of its scope, so it can be accessed and called before its actual declaration in the code.
So, when the code is executed, the greet()
function will be available and can be called without any errors. When greet()
is called, it will simply output "Hi, there."
to the console.
Another example
function greet() {
console.log("Hello, " + name);
var name = "Alice";
}
greet();
Output:
In this code snippet, the greet()
function tries to log a greeting message that includes the name
variable, which is not defined yet. However, because of hoisting, the variable declaration of name
is moved to the top of the greet()
function scope during the compilation phase. So, the code is actually interpreted like this:
function greet() {
var name; // Declaration is moved to the top
console.log("Hello, " + name); // Output: Hello, undefined
name = "Alice";
}
greet();
Therefore, it’s best practice to always declare and initialize variables before using them to avoid confusion and potential bugs in your code.
Do comment if you have any doubts or suggestions on this JS topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version