LET and CONST
-
Definições
- const for values that we will not change change.
- let like the old var, for values that we wanna change or mutate later on.
- Function-scoped and Block-scoped
- Undefined
- Blocks
Diferenças
Variables declared with var in the ES5 are function-scoped but variables
declared with let on ES6 are block-scoped.
// Everything inside the driversLicence6 function, is it's scope.
// With that, in ES5 we have access to everything inside the scope.
// However, in ES6, we only have access to what is in the blocks.
// With that, you can not access firstName and yearOfBirth from outside the if statment,
// being that you would be trying to access something from outside it's block.
function driversLicence6(passedTest) {
if (passedTest) {
// this is a block - the if statement
let firstName = 'John';
const yearOfBirth = 1990; // impossible to change the birth year.
}
// this is a block - this will not work because it doesn't have access to firstName and yearOfBirth, being that they are in another block.
console.log(firstName + ', born in ' + yearOfBirth + ', is now officially allowed to drive a car.');
}
How to make it work:
Declare the variables outside the function.
function driversLicence6(passedTest) {
let firstName; let doesn't need to have it's value defined here.
const yearOfBirth = 1990; const must have it's value defined here.
if (passedTest) {
let firstName = 'John'; defined value for let
}
console.log(firstName + ', born in ' + yearOfBirth + ', is now officially allowed to drive a car.');
}
driversLicence6(true); // the person passed the test.
// ES 5
function driversLicence5(passedTest) {
console.log(firstName);
if (passedTest) {
var firstName = 'John';
var yearOfBirth = 1990;
}
}
Ocorre um erro: firstName is undefined, visto que o JS tenta executar a variable antes dela receber um valor, no momento ela só foi lida para o JS saber que ela existe.
// ES 5
var i = 23;
for (var i = 0; i < 5; i++) {
console.log(i); // exibe 0, 1, 2, 3, 4
}
console.log(i); //exibe 5, pois vai ser 4++, quando chegar no if vai ser false, não executando-o, porém será exibido nesse console.log.
// ES 6
let i = 23;
for (let i = 0; i < 5; i++) {
console.log(i); // exibe 0, 1, 2, 3, 4
}
console.log(i); // exibe 23, visto que as duas variáveis estão em diferentes blocks.
Nesse caso, seria como possuir uma var dentro do for e uma var fora.