ES6 Features - Article #1
Table of contents
Const
In ES6, the const
keyword is introduced to create constant variables which can't be reassigned after their initial assignment. Attempting to reassign the const
variables will get the TypeError: Assignment to constant variable.
Here is an example of using const
const PI = 3.141593
// TypeError: Assignment to constant variable
// PI = 2
We can also create the constant variable in ES5 using Object.defineProperty
Object.defineProperty(typeof global === 'object' ? global : window, "PI", {
value: 3.141593,
enumerable: true,
writable: false,
configurable: false
})
let (Block Scope Variable)
let
is an alternative to var
for variable declarations. Unlike var
, variables declared with let
have block scope(enclosed by curly braces).
let callbacks = []
for (let i = 0; i <= 5; i++)
callbacks[i] = function() { return i * 2 }
callbacks.forEach(func => {
console.log(func())
})
// 0
// 2
// 4
// 6
// 8
// 10
Here is the implementation with ES5
var callbacks = []
for (var i = 0; i <= 5; i++)
(function(i){
callbacks[i] = function() { return i * 2 }
})(i)
callbacks.forEach(func => {
console.log(func())
})
// 0
// 2
// 4
// 6
// 8
// 10
Arrow Functions
Arrow functions provide a more compact syntax compared to traditional function expressions, and they also behave differently in terms of how they handle the this
keyword.
evens = [2, 4, 6, 8, 10]
// expression body
odds = evens.map(v => v + 1)
console.log(odds); // [3, 5, 7, 9, 11]
// statement body
threes = []
odds.map(v => {
if (v % 3 === 0)
threes.push(v)
})
// lexical this
function ArrowLexicalThis() {
this.fives = []
this.nums = [1, 3, 5, 7, 9, 12, 15, 18, 20]
this.nums.forEach((v) => {
if (v % 5 === 0)
this.fives.push(v)
})
console.log(this.fives)
}
new ArrowLexicalThis() // [ 5, 15, 20 ]
Here is the traditional function expressions
evens = [2, 4, 6]
odds = evens.map(function(v) { return v + 1 })
// statement body
threes = []
odds.map(function(v) {
if (v % 3 === 0)
threes.push(v)
})
// lexical this
function ArrowLexicalThis() {
this.fives = []
this.nums = [1, 3, 5, 7, 9, 12, 15, 18, 20]
self = this;
this.nums.forEach(function(v) {
if (v % 5 === 0)
self.fives.push(v)
})
console.log(this.fives)
}
new ArrowLexicalThis() // [ 5, 15, 20 ]