Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

What's the difference between using “let” and “var”?

ECMAScript 6 introduced the let statement.

I've heard that it's described as a local variable, but I'm still not quite sure how it behaves differently than the var keyword.

What are the differences?. When should let be used instead of var?
by

3 Answers

akshay1995
let is interesting, because it allows us to do something like this:

(() => {
var count = 0;

for (let i = 0; i < 2; ++i) {
for (let i = 0; i < 2; ++i) {
for (let i = 0; i < 2; ++i) {
console.log(count++);
}
}
}
})();

Which results in counting [0, 7].

Whereas

(() => {
var count = 0;

for (var i = 0; i < 2; ++i) {
for (var i = 0; i < 2; ++i) {
for (var i = 0; i < 2; ++i) {
console.log(count++);
}
}
}
})();

Only counts [0, 1].
RoliMishra
In most basic terms,
for (let i = 0; i < 5; i++) {
// i accessible
}
// i not accessible

for (var i = 0; i < 5; i++) {
// i accessible
}
// i accessible
pankajshivnani123
he main difference is the scope difference, while let can be only available inside the scope it's declared, like in for loop, var can be accessed outside the loop for example. From the documentation in MDN (examples also from MDN):

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

Variables declared by let have as their scope the block in which they are defined, as well as in any contained sub-blocks. In this way, let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function:

function varTest() {
var x = 1;
if (true) {
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}

function letTest() {
let x = 1;
if (true) {
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}`

At the top level of programs and functions, let, unlike var, does not create a property on the global object. For example:

var x = 'global';
let y = 'global';
console.log(this.x); // "global"
console.log(this.y); // undefined

When used inside a block, let limits the variable's scope to that block. Note the difference between var whose scope is inside the function where it is declared.

var a = 1;
var b = 2;

if (a === 1) {
var a = 11; // the scope is global
let b = 22; // the scope is inside the if-block

console.log(a); // 11
console.log(b); // 22
}

console.log(a); // 11
console.log(b); // 2

Also don't forget it's ECMA6 feature, so it's not fully supported yet, so it's better always transpiles it to ECMA5 using Babel etc... for more info about visit babel website

Login / Signup to Answer the Question.