Variables, hoisting, and the temporal dead zone in JavaScript

Photo by Christopher Robin Ebbinghaus on Unsplash

Introduction:

Variable hoisting is one of the simplest but still misunderstood concepts in JavaScript. There are still a few of us who feel that in Javascript variable declaration is physically moved to the top of the function block. Although conceptually it is much simpler to visualize and understand the variable being physically moved to the top, that is not how it happens.

function test() {
console.log(myVar);
var myVar = 10;
console.log(myVar);
}
test();
// Output
> undefined
> 10

Understanding the output

The simple way: The variable declarations are hoisted, and that essentially means the above code gets interpreted as

function test() {
var myVar;
console.log(myVar);
myVar = 10;
console.log(myVar);
}
test();
function test() {
console.log(myVar);
let myVar = 10;
console.log(myVar);
}
test();
// Output
> VM94:2 Uncaught ReferenceError: Cannot access 'myVar' before initialization
at test (<anonymous>:2:14)
at <anonymous>:6:1
function test() {
console.log(typeof myUndefinedVariable);
console.log(typeof myVar);
let myVar = 10;
}
test();
// Output
> undefined
> VM114:3 Uncaught ReferenceError: Cannot access 'myVar' before initialization
at test (<anonymous>:3:10)
at <anonymous>:6:1

References:

Sr. Software Developer at SpringerNature Technology and Publishing Solutions