JavaScript uses the let keyword to declare variables. Although the var keyword can also be used to declare variables, their main distinction is in the scopes they have. Let is block scoped, whereas var is function scoped; we shall go into more detail on this later.
Understanding how the let keyword differs from var is crucial for understanding it.
Function Scope
var example
function func() {
// x is known here but not defined.
console.log('value of x here: ', x)
{
var x = 10;
x = x + 5;
}
// x is still known here and has a value.
console.log('value of x after for block: ', x)
}
// x is NOT known here.
func()
let example
function func() {
// x is NOT known here. Try uncommenting the line below.
// console.log('value of x here: ', x)
{
let x = 10;
x = x + 5;
}
// x is NOT known here. Try uncommenting the line below.
// console.log('value of x after for block: ', x)
}
// x is NOT known here.
func()
The first tab in the code sample above uses var; take note of how var is declared in line 5 within a block. Above the block, this variable is known (but undefined). After the block, it is known and defined, though.
The places where x has a scope are represented by the highlighted lines. Var is referred to as having function scope because it encompasses the entire function.
Note that x is only known and defined within the block it is declared in—the highlighted lines—in the second code tab, where it is declared using let in line 5. Everywhere outside of its block is outside of its scope.
Block scope
Take into account the following illustration to further illustrate the block scope for let:
var example
var mango = "yellow"
if (mango === "yellow"){
var mango = "blue"
console.log(mango)
}
console.log(mango)
let example
let mango = "yellow"
if (mango === "yellow"){
let mango = "blue"
console.log(mango)
}
console.log(mango)
Using let
Inside the if block, mango is first declared as “yellow” in line 1 and then redeclared as “blue” in line 4. The mango stated inside the if block, however, only has scope inside that block, as the output demonstrates. The original mango variable with the value “yellow” is accessible outside of this block.
Using var
On the other hand, changing the mango defined in line 1 to “blue” inside the if block in the code that uses var also affects the mango declared in line 1. This is so that block scope is irrelevant when variables declared using var are defined