JavaScript Hoisting (With Examples)
JavaScript Hoisting (With Examples)
(https://programiz.pro?utm_source=programiz-top-
CODING Try hands-on coding bar&utm_campaign=programiz&utm_medium=referral)
PRO with Programiz PRO
36% OFF Claim Discount Now
JavaScript Hoisting
In this tutorial, you will learn about JavaScript hoisting
with the help of examples.
Variable Hoisting
In terms of variables and constants, keyword var is
hoisted and let and const does not allow hoisting.
For example,
(https://programiz.pro?utm_source=programiz-top-
CODING Try hands-on coding bar&utm_campaign=programiz&utm_medium=referral)
PRO with Programiz PRO
36% OFF Claim Discount Now
However in JavaScript, initializations are not hoisted. For
example,
Search tutorials & examples
(/)
www.domain-name.com
// program to display value
console.log(a);
var a = 5;
Output
undefined
var a;
console.log(a);
a = 5;
(https://programiz.pro?utm_source=programiz-top-
CODING Try hands-on coding bar&utm_campaign=programiz&utm_medium=referral)
PRO with Programiz PRO
36% OFF Claim Discount Now
function greet() {
b = 'hello';
console.log(b); // hello
var b;
}
greet(); // hello
console.log(b);
Output
hello
Uncaught ReferenceError: b is not defined
If a variable is used
Search with the
tutorials let keyword, that variable is
& examples
(/)
not hoisted. For example,
www.domain-name.com
Output
Function Hoisting
A function can be called before declaring it. For example,
function greet() {
console.log('Hi, there.');
}
Output
Thank you for printing our content at www.domain-name.com. Please check back soon for new
Hi, there
contents.
(https://programiz.pro?utm_source=programiz-top-
CODING TryIn the above
hands-on program, the function greet is called before
coding bar&utm_campaign=programiz&utm_medium=referral)
PRO declaring
with ProgramizitPRO
and the program shows the output. This is due
36% OFF Claim Discount Now
to hoisting.
Output
If var was used in the above program, the error would be:
Previous Tutorial:
(/javascript/variable-scope)
JS Variable Scope
Share on:
(https://www.facebook.com/sharer/sharer.php? (https://twitter.com/in
u=https://www.programiz.com/javascript/hoisting) text=Check%20this%
(/javascript/variable-scope)
JavaScript Tutorial
JavaScript Classes
(/javascript/classes)
JavaScript Tutorial
(/javascript/function)