ES6 summary Chapter 1: about let and const keyword
let
let
keyword is used for declaring variable, but it has block scope. If it is outside, then it will suffer the ReferenceError.- Notice: the
let
keyword doesn’t allow to duplicatedly declare the variable, even if you use thevar
orconst
. Will throw an error. - The benefits of using let:
- we will no longer use the IIFE to build a block scope.
- we will no longer use the closure to build a block scope.
- Notice:
In ES6, the scope of a function is also inside its block scope.
function f() { console.log('I am outside!');
;(function() {
if(false) {
//declare the function again
function f() { console.log('I am inside!');
}
f();
}());
For this situation, if under ES5, we will get ‘I am outside!’, if under es6, we will get 'I am inside!’.
5. The let
will not hoist the variable like var
keyword.
const
- If declared by using const, we will never change the value again.
- If we declare the value again, we will not get an error, the system will just ignore it.
- The const is the same with let, they both has the block scope.
- The same with let, cannot duplicatedly declare the variable, will also throw an error.