ES2016 & ES2017
Reference
January 30, 2018
The next section of the class I’m doing builds on the ES2015 section and shows what’s new in ES2016 and ES2017.
For reference:
- Exponentiation Operator
- Includes Method with Arrays
- padStart and padEnd
- Async Functions
- Object & Class Async
- Async Error Handling
- Sequential vs. Concurrent Async Requests (HTTP)
Exponentiation Operator
Now there is a shorthand way to calculate exponents:
//ES2015 |
This also works with the equals =
operator to accumulate exponents:
// ES2015 |
Includes Method with Arrays
Now the includes()
method is available to check for values in an array as well as strings:
// ES2015 |
padStart and padEnd
If you need to pad a string to be a specific length, these methods let you do it. The first parameter is the total desired length, and the second is the character to pad with (empty spaces if 2nd param is omitted):
"awesome".padStart(10); // " awesome" |
Async Functions
Async functions simplify writing promises: with the await
keyword (which can only be used inside async
functions) you can pause the execution of the function to wait for a Promise to be resolved.
async function getMovieData(){ |
Object & Class Async
Object methods can also get async function with the async
keyword:
var movieCollector = { |
Similarly, async functions can be included within a class constructor:
class MovieData { |
Async Error Handling
To handle errors with async functions, you can use a try/catch statement:
async function getUser(user){ |
Sequential vs. Concurrent Async Requests
If you run multiple async requests within a function, each will wait in turn until the previous is resolved. In the example below responseTwo
does not make the HTTP request until responseOne
resolves:
async function getMovieData(){ |
This should be refactored to start the HTTP requests in parallel, and then await their resolved promises:
async function getMovieData(){ |
We can also use Promise.all()
to await multiple resolved promises:
async function getMovieData(first, second){ |
Object Rest & Spread
A proposed change in ES2017 is to introduce the rest & spread ...
operator to objects. This would gather the rest of the keys and values in an object and create a new object out of them:
var instructor = {first:"Elie", last:"Schoppik", job:"Instructor", numSiblings:3}; |
You can also spread out keys and values to move them from one object to another:
var instructor = {first:"Elie", last:"Schoppik", job:"Instructor"}; |
The spread operator can also be used to assign default values more concisely than the Object.assign()
method:
var defaults = {job: "Instructor", ownsCat:true, ownsDog: true}; |
Up Next
Next section we start on D3 and data visualizations!