By the end of this lesson, students will be able to:
- Compare/contrast features of ES5 and ES6
- Shorten methods and properties with new ES6 syntax
- Use template literals to minimize string concatenation
- Use arrow functions to simplify anonymous function definitions
- Use the spread operator to manage an array of input
ES6 allows us to shorten method definitions from:
var car = {
drive: function(){
console.log("vroom")
}
}
to
let car = {
drive(){
console.log("vroom")
}
}
And for properties where the key is the same as the variable storing the value:
// es5
let x = 1
let y = 2
let obj = {x:x, y:y}
// vs
//es6
let obj = {x,y}
Use both of these concise syntaxes in the exercise below:
Remember string concatenation in Javascript?
var name = "Inigo Montoya"
var killee = "father"
var prepareTo = "die"
console.log("Hello. My name is "+ name + ". You killed my " + killee +". Prepare to " + prepareTo)
Annoying to try and remember all of those +
signs right? In ES6, we can interpolate variables using template literal syntax:
let name = "Inigo Montoya"
let killee = "father"
let prepareTo = "die"
console.log(`Hello. My name is ${name}. You killed my ${killee}. Prepare to ${prepareTo}`)
Way easier, right?
Arrow functions are a new shorthand syntax for defining anonymous functions:
let foods = ["pizza","mac n cheese","lasagna"]
foods.forEach( food => console.log(`I love ${food}`) )
// vs the old
foods.forEach(function(food){
console.log("I love " + food)
})
If there is more than one argument to the anonymous function, wrap them in parens:
let foods = ["pizza","mac n cheese","lasagna"]
foods.forEach( (food,i) => console.log(`My #${i} favorite food is ${food}`) )
Arrow functions also have the benefit of lexical scoping, which is a fancy way of saying it uses “this” from the surrounding code: the code that contains the code in question. See how this can be helpful below:
//Function scoped in ES5
var pizza = {
temperature: 0,
toppings: ["cheese", "ham", "pineapple"],
bake() {
setInterval(function(){
this.temperature++ // doesn't work because this is GLOBAL. The setInterval function belongs to the window object.
}, 1000)
}
}
// vs Lexically Scoped in ES6
var pizza = {
temperature: 0,
toppings: ["cheese", "ham", "pineapple"],
bake() {
setInterval( () => {
this.temperature++
}, 1000)
}
}
Additionally, the return
statement is not needed with single line arrow functions. There is an implicit return.
let add = (x, y) => x + y
If the function is multi-line, you need to explicitly return:
let add = (x,y) => {
console.log(x + y)
return x + y
}
Hint: If you are stuck on the
reduce
part of the exercise below, remember you can include an initial value after your arrow function (0 perhaps?).
The spread operator ...
allows an expression to be expanded into multiple elements.
This is useful for separating an array into individual elements:
let dimensions = [10, 5, 2];
let volume = function(height, width, length){
return height * width * length;
}
volume(...dimensions);
// versus
volume(dimensions[0], dimensions[1], dimensions[2])
This also makes it very easy to create copies of an array in functions where mutation occurs:
var days = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
function reversedDays(arr){
return arr.reverse()
}
console.log(reversedDays(days))
// but now days is no longer in order
console.log(days)
// To deal with this, we can either:
function reversedDays(arr){
var newArray = []
for(let i = 0; i < arr.length; i++){
newArray.push(arr[i])
}
return newArray.reverse()
}
console.log(reversedDays(days))
console.log(days)
// or... (<- pun)
function reversedDays(arr){
return [...arr].reverse()
}
console.log(reversedDays(days))
console.log(days)
Challenge: How might you use template literals, a spread operator, and an array of name
, day
, and adjective
, to make a greeting function that prints out:
Hello, Zeb, today is Tuesday, isn't it a wonderful day?
Tweak the values of those variables and test it again.
Support for ES6 is great! - https://kangax.github.io/compat-table/es6/
If you need to support a legacy browser, check out the following tools:
There are lots more features of ES6 that we have not covered: