Hoisting in JavaScript is a behavior in which a function or a variable can be used before declaration.For example,
// using test before declaring
console.log(test); // undefined
var test;
1. Variable Hoisting
In terms of variables and constants, keyword var
is hoisted and let
and const
does not allow hoisting.Variables defined with let
and const
are hoisted to the top of the block, but not initialized.
// program to display value
var a;
a = 5;
console.log(a); // 5
If a variable is used with the let
keyword, that variable is not hoisted. For example,
// program to display value
a = 5;
console.log(a);
let a; // error.
//output:Uncaught ReferenceError: Cannot access 'a' before initialization
However in JavaScript, initializations are not hoisted. For example,
// program to display value
console.log(a);
var a = 5;
//output:
undefined
JavaScript Initializations are Not Hoisted
Example 1:
var x = 5; // Initialize x
var y = 7; // Initialize y
elem = document.getElementById(“demo”); // Find an element
elem.innerHTML = x + “ “ + y; // Display x and y
=> Ouput: 5 7
Example 2:
var x = 5; // Initialize x
elem = document.getElementById(“demo”); // Find an element
elem.innerHTML = x + “ “ + y; // Display x and y
var y = 7; // Initialize y
Example 3:
var x = 5; // Initialize x
var y; // Declare y
elem = document.getElementById(“demo”);
// Find an element
elem.innerHTML = x + “ “ + y; // Display x and y
y = 7; // Assign 7 to y
=> Ouput: 5 undefined
Also, when the variable is used inside the function, the variable is hoisted only to the top of the function. For example,
// program to display value
var a = 4;
function greet() {
b = 'hello';
console.log(b); // hello
var b;
}
greet(); // hello
console.log(b);
Ouput:
hello
Uncaught ReferenceError: b is not defined
In the above example, variable b is hoisted to the top of the function greet
and becomes a local variable. Hence b is only accessible inside the function. b does not become a global variable.
2. Function Hoisting
// program to print the text
greet();
function greet() {
console.log('Hi, there.');
}output: Hi, there
However, when a function is used as an expression, an error occurs because only declarations are hoisted. For example;
// program to print the text
greet();
let greet = function() {
console.log('Hi, there.');
}//output:
Uncaught ReferenceError: greet is not defined