A keyword let
permite criarmos escopos de bloco no JavaScript. Sem muito bláblá, vamos direto ao ponto.
Escopo de bloco
Utilizando 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 |
Utilizando 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
Utilizando 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 |
Utilizando 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 |
Variáveis duplicadas
Utilizando 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 |
Utilizando 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' |
Aqui você encontra um JS Bin com os exemplos acima.