// *** before: ***
var x = 10;
if (true) {
var x = 20;
console.log(x); // 20
}
console.log(x); // 20 - var has no block scope
for (var i = 0; i < 3; i++) {
setTimeout(function () { console.log(i); }, 0);
}
// prints 3, 3, 3 - one i shared by every iteration
// *** in version ES2015: ***
let x = 10;
if (true) {
let x = 20;
console.log(x); // 20
}
console.log(x); // 10 - the block has its own scope
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// prints 0, 1, 2 - each iteration gets its own i
const PI = 3.14;
// PI = 3; // TypeError: Assignment to constant variable.