Search⌘ K
AI Features

Var vs Let vs Const and the temporal dead zone

Explore the distinctions between var let and const declarations in JavaScript ES6 including their scoping rules and behavior. Understand the temporal dead zone concept that prevents access to let and const variables before they are initialized, improving code reliability and debugging. This lesson helps you know when and how to use each keyword effectively in your code.

With the introduction of let and const in ES6, we can now better define our variables depending on our needs. During our JavaScript primer we looked at the basic differences between these 3 keywords, now we will go into more detail.

 

Var #

Variables declared with the var keyword are function scoped, which means that if we declare them inside a for loop (which is a block scope), they will be available even outside of it.

Javascript (babel-node)
for (var i = 0; i < 10; i++) {
var leak = "I am available outside of the loop";
}
console.log(leak);
// I am available outside of the loop

Let’s take a look at an example with a functional scope variable:

Javascript (babel-node)
function myFunc(){
var functionScoped = "I am available inside this function";
console.log(functionScoped);
}
myFunc();
// I am available inside this function
console.log(functionScoped);
// ReferenceError: functionScoped is not defined

In the first example, the value of the var leaked out of the block scope and could be accessed from outside of it. Whereas in the second example, var was confined inside a function-scope, and we could not access it from outside.

 

Let

...