ES2015: let & const
What is ES2015?
ES2015, also known as ES6 is the most extensive update to the JavaScript language since 1997.
Problems with var
In ES5, we use var
to declare variables in JavaScript, but var
comes with some minor problems like:
var
follows functional scope, which means only declaring a function creates a new scope, blocks likecurly braces {}
do not.
var x = 10; // global x
function one() {
var x = 5; // local x
console.log(x);
}
function two() {
x = 15; // global x
}
one(); // 5
console.log(x); // 10
two();
console.log(x); // 15
- Hoisting, which means that any variable declaration done using
var
is moved to the top of the current scope.
x = 10; // Does not throw refrenceError
console.log(x); // 10
var x; // Declare x
Here x
can be used before being declared because JavaScript engine hoists it to the top of the current scope.
let & const
In ES2015, let
& const
are introduced to address the problems with usage of var
.
-
let
, is same asvar
but it follows the more intuitve block scope, which meanscurly braces {}
create a new scope for variables declared withlet
. -
const
, is same aslet
but it is used to declare constants, meaning once declared values of variables declared withconst
cannot be altered.
Example of block scoping
let x = 10; // global x
if(true) {
let x = 15; // local x
console.log(x); // 15
}
console.log(x); // 10
let in for loops
var arr = [1,2,3];
/**
* With var, for loop prints
* 3
* 3
* 3
*/
for(var i in arr) {
setTimeout(function () {
console.log(arr[i]);
},0);
}
/**
* With let, for loop prints
* 1
* 2
* 3
* as let creates a new copy of i for each block iteration
*/
for(let i in arr) {
setTimeout(function () {
console.log(arr[i]);
},0);
}
let Gotchas
let x = 5;
x = 10; // reassigning is allowed
/* redecleration within same scope is not allowed */
let x = 'Hello';
let x = 'World'; // TypeError: identifier 'x' has already been declared
if(true) {
let x = 'World'; // new scope
}
const examples
/* const are read-only */
const MAX_LIMIT = 50;
MAX_LIMIT = 100; // TypeError: Assignment to constant variable
/* const require an initial value */
const MAX_LIMIT; // SyntaxError: Missing initializer in const decleration
Important: const
are also block scoped just like let
conclusions
- Use
const
when you want to declare variable whose values would not and should not change. - Use
let
for all other places where you would have usedvar
. - Avoid
var
until unless the use case requires it.
Written on April 7, 2017