...

/

Var vs Let vs Const and the temporal dead zone

Var vs Let vs Const and the temporal dead zone

Learn the new ways of declaring variables introduced in ES6.

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.

Press + to interact
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:

Press + to interact
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

...

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy