JS Tutorial
JS Version
JS Objects
JS Function
JS Classes
JS Async
JS HTML DOM
JS Browser BOM
JS Web API
JS AJAX
JS JSON
JS vs JQUERY
JS Graphics
JavaScript Hoisting
Hoisting defines JavaScript’s default behavior of shifting the declarations to the top.
JavaScript Declarations are Hoisted
In JavaScript, a variable can be declared after it has been used.
In other words; a variable can be used before it has been declared.
Example
<!DOCTYPE html>
<html>
<body>
<p id=”demo”></p>
<script>
x = 5; // Assign 5 to x
elem = document.getElementById(“demo”); // Find an element
elem.innerHTML = x; // Display x in the element
var x; // Declare x
</script>
</body>
</html>
Output
The let and const Keywords
Variables specified with let and const are hoisted to the top of the block, but initialization is not done.
A let variable is used before it is declared, generating a result in a ReferenceError.
The variable is in a “temporal dead zone” from the begining of the block until it is declared:
Example
This results in a ReferenceError:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Hoisting</h2>
<p>With <b>let</b>, you cannot use a variable before it is declared.</p>
<p id=”demo”></p>
<script>
try {
carName = “Saab”;
let carName = “Volvo”;
}
catch(err) {
document.getElementById(“demo”).innerHTML = err;
}
</script>
</body>
</html>
Output
JavaScript Hoisting
With let, you cannot use a variable before it is declared.
ReferenceError: Cannot access 'carName' before initialization
A const variable is usd before it is declared, is a syntax error, so the code simply does not run.
Example
This code will not run.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Hoisting</h2>
<p>With <b>const</b>, you cannot use a variable before it is declared.</p>
<p>Try to remove the //.</p>
<p id=”demo”></p>
<script>
carName = “Volvo”;
//const carName;
document.getElementById(“demo”).innerHTML = carName;
</script>
</body>
</html>
Output
JavaScript Hoisting
With const, you cannot use a variable before it is declared.
Try to remove the //.
Volvo
JavaScript Initializations are Not Hoisted
JavaScript only hoists declarations, not initializations.
Example
<!DOCTYPE html>
<html>
<body>
<p id=”demo”></p>
<script>
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
</script>
</body>
</html>
Output
5 7