Function Scope v.s. Block Scope
ES2015(aka ES6) introduced a new keyword let that declares a new variable in block scope. Before that, most JavaScript variables are function scope or global scope.
Function Scope
Following example shows the scope of variable num declared by var.1
2
3
4
5
6
7(function () {
{
var num = 1;
console.log(num); // 1
}
console.log(num); // 1. Same variable as defined in {}.
}());
Block Scope
Following example shows the scope of variable num declared by let.1
2
3
4
5
6
7(function () {
{
let num = 1;
console.log(num); // 1
} // num goes out of scope.
console.log(num); // ReferenceError: num is not defined.
}());
Hoisting
Variables declared by var are hoisted.1
2
3
4
5
6
7(function () {
console.log(num); // undefined
{
var num = 1;
console.log(num); // 1
}
}());
Variables declared by let are not hoisted.1
2
3
4
5
6
7(function () {
console.log(num); // ReferenceError: num is not defined.
{
let num = 1;
console.log(num); // 1
}
}());
Block Scope Before ES2015
Variables declared in the catch clause of try...catch statement is block scoped.