The keyword let
allows us to create block scopes in JavaScript. Let’s see some examples.
Block scope
Using var
.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var me = 'James Bond'; | |
if(true) { | |
var me = 'Chuck Norris'; | |
} | |
console.log(me); | |
// Chuck Norris |
Using let
.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let me = 'James Bond'; | |
if(true) { | |
let me = 'Chuck Norris'; | |
} | |
console.log(me); | |
// James Bond |
Loops
Using var
.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
for(var i = 0; i < 5; i++) { | |
// ... | |
} | |
console.log(i); | |
// 5 |
Using let
.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
for(let i = 0; i < 5; i++) { | |
// ... | |
} | |
console.log(i); | |
// ReferenceError: i is not defined |
Duplidated variables
Using var
.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var country = 'Brazil'; | |
//.. | |
//.. | |
//.. | |
var country = 'Belgium'; | |
console.log(country); | |
// Belgium |
Using let
.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let country = 'Brazil'; | |
//.. | |
//.. | |
//.. | |
let country = 'Belgium'; | |
console.log(country); | |
// Duplicate declaration 'country' |
Here you can find an JS Bin with the examples.