Hoisting is JavaScript’s default behavior of moving 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.
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
Output: An element with 5 inside
it is the same as:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var x; // Declare x
x = 5; // Assign 5 to x
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x; // Display x in the element
</script>
</body>
</html>
To understand this, you have to understand the term “hoisting”.
Hoisting is JavaScript’s default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).
let and const
Variables declared with
let
and
const
eliminate this specific issue of hoisting because they’re scoped to the block, not to the function. Previously, when you used
var
, variables were either scoped globally or locally to an entire function scope.
If a variable is declared using
let
or
const
inside a block of code (denoted by curly braces
{ }
), then the variable is stuck in what is known as the temporal dead zone until the variable’s declaration is processed. This behavior prevents variables from being accessed only until after they’ve been declared.
function getClothing(isCold) {
if (isCold) {
const freezing = 'Grab a jacket!';
} else {
const hot = 'It’s a shorts kind of day.';
console.log(freezing);
}
}
The output is : “freesing is not defined”, because of the TDZ.