The main difference between var and let is pretty simple:
let has a "block scope"
and
var has a "function scope"
Here are some examples:
Example 1 - using let:
for (let x=1; x<=5; x++)
console.log(x); // 1 … 5
console.log(x); // Ref. error
function test() {
console.log(x); // Ref. error
let x = 5;
}
test();
Example 1 - using var (the same code but with var instead of let):
for (var x=1; x<=5; x++)
console.log(x); // 1 … 5
console.log(x); // 6
function test() {
console.log(x); // undefined
var x = 5;
}
test();
Example 2 - using let:
let x = 100; // block scope
console.log(x); // 100
for (let x=1; x<=5; x++) {
console.log(x); // 1 … 5
} // end of block scope
console.log(x); // 100
console.log(x); // Ref. error
let x;
Example 2 - using var(the same code but with var instead of let):
var x = 100; // function scope
console.log(x); // 100
for (var x=1; x<=5; x++) {
console.log(x); // 1 … 5
} // same x inside the loop
console.log(x); // 6
console.log(x); // undefined
var x;