ES2016

Exponentiation Opertor **

Replace Math.pow

ES2015

In [3]:
var calculatedNumber = Math.pow(2,4);
calculatedNumber;
Out[3]:
16

ES2016

In [4]:
var calculatedNumber = 2**4;
calculatedNumber;
Out[4]:
16

ES2015

In [5]:
var nums = [1,2,3,4];
var total = 2;

for(let i = 0; i < nums.length; i++){
  total = Math.pow(total, nums[i]);
}
Out[5]:
16777216

ES2016

In [6]:
var nums = [1,2,3,4];
var total = 2;

for(let i = 0; i < nums.length; i++){
  total **= nums[i];
}
Out[6]:
16777216

[].includes

Works like includes in strings but now on arrays Replace indexOf in arrays

ES2015

In [7]:
var nums = [1,2,3,4,5];
nums.indexOf(3) > -1;
Out[7]:
true
In [8]:
nums.indexOf(44) > -1;
Out[8]:
false

ES2016

In [9]:
var nums = [1,2,3,4,5];
nums.includes(3);
Out[9]:
true
In [10]:
nums.includes(44);
Out[10]:
false

ES2017

padStart, padEnd

  • The first parameter is the total length of the new string
  • The second parameter is what to pad with from the start/end. The default is an empty space

padStart

In [12]:
"awesome".padStart(10);
Out[12]:
'   awesome'
In [13]:
"awesome".padStart(10,'!');
Out[13]:
'!!!awesome'

padEnd

In [14]:
"awesome".padEnd(10,'!');
Out[14]:
'awesome!!!'

Async Functions

  • A special kind of function that is created using the word async
  • The purpose of async functions is to simplify writing asynchronous code, specifically Promises.
  • Async functions can be used as methods inside an object (see example below)
In [16]:
async function first(){
  return "We did it!";
}

first(); // returns a promise
Out[16]:
'We did it!'
In [15]:
first().then(val => console.log(val));
We did it!

Async Functions: Await

  • await pauses the execution of the async function and is followed by a Promise. The await keyword waits for the promise to resolve, and then resumes the async function's execution and returns the resolved value.
  • A reserved keyword that can only be using inside async functions
  • Think of the await keyword like a pause button (similar to yield with generators)
async function getMovieData(){
  console.log("starting!");
  var movieData = await $.getJSON('https://omdbapi.com?t=titanic&apikey=thewdb');
  // this line does NOT run until the promise is resolved!
  console.log("all done!");
  console.log(movieData);
}

getMovieData() // logs an object with data about the movie!

// No .then or callback or yield necessary!

Object Async

var movieCollector = {
  data: "titanic",
  async getMovie(){
    var response = await $.getJSON(`https://omdbapi.com?t=${this.data}&apikey=thewdb`);
    console.log(response);
  }
}

movieCollector.getMovie();

Class Async (ES2015)

class MovieData {
  constructor(name){
    this.name = name;
  }
  async getMovie(){
    var response = await $.getJSON(`https://omdbapi.com?t=${this.name}&apikey=thewdb`);
    console.log(response);
  }
}

var m = new MovieData('shrek');
m.getMovie();

Async Functions: Error Handling

  • If a promise is rejected using await, an error with be thrown so we can easily use a try/catch statement to handle errors

Using try and catch block

async function getUser(user){
  try {
    var response = await $.getJSON(`https://api.github.com/users/${user}`);
    console.log(response.name);
  } catch(e){
    console.log("User does not exist!");
  }
}

getUser('elie'); // Elie Schoppik
getUser('foo'); // User does not exist!

Async Functions: HTTP Requests

  • Bad: The next HTTP request does not get made until the previous promise is resolved.
  • Better: Start the HTTP requests in parallel and then await their resolved promise!
  • We can use Promise.all with await multiple resolved promises
    • Promise.all returns an array of Promise

SEQUENTIAL NOT PARALLEL

async function getMovieData(){
  var responseOne = await $.getJSON(`https://omdbapi.com?t=titanic&apikey=thewdb`);
  var responseTwo = await $.getJSON(`https://omdbapi.com?t=shrek&apikey=thewdb`);
  console.log(responseOne);
  console.log(responseTwo);
}

getMovieData();

MUCH FASTER!

async function getMovieData(){
  var titanicPromise = $.getJSON(`https://omdbapi.com?t=titanic&apikey=thewdb`);
  var shrekPromise = $.getJSON(`https://omdbapi.com?t=shrek&apikey=thewdb`);

  var titanicData = await titanicPromise;
  var shrekData = await shrekPromise;

  console.log(titanicData);
  console.log(shrekData);
}

getMovieData();

SAME but use Promise.all

async function getMovieData(first, second){
  var moviesList = await Promise.all([
    $.getJSON('https://omdbapi.com?t=${first}&apikey=thewdb'),
    $.getJSON('https://omdbapi.com?t=${second}&apikey=thewdb')
  ]);
  console.log(moviesList[0].Year);
  console.log(moviesList[1].Year);
}

getMovieData('shrek', 'blade');

// 2001
// 1998

Exercise: Async Functions (pending)

1) Write a function called hasMostFollowers, which accepts a variable number of arguments. You should then make an AJAX call to the Github User API (https://developer.github.com/v3/users/#get-a-single-user) to get the name and number of followers of each argument. The function should return a string which displays the username who has the most followers.

Hint - Try to use Promise.all to solve this and remember that the jQuery AJAX methods ($.getJSON, $.ajax, etc.) return a promise.

hasMostFollowers('elie','tigarcia','colt').then(function(data){
    console.log(data)
});

//output: "Colt has the most followers with 424"*/

2) Write a function called starWarsString, which accepts a number. You should then make an AJAX call to the Star Wars API (https://swapi.co/ ) to search for a specific character by the number passed to the function. Your function should return a promise that when resolved will console.log the name of the character.

starWarsString(1).then(function(data){
    console.log(data)
})

// output: "Luke Skywalker" */

Bonus 1 - Using the data from the previous AJAX call above, make another AJAX request to get the first film that character is featured in and return a promise that when resolved will console.log the name of the character and the film they are featured in

starWarsString(1).then(function(data){
    console.log(data)
})

// output: "Luke Skywalker is featured in The Empire Strikes Back,
//directed by Irvin Kershner"

Bonus 2 - Using the data from Bonus 1 - make another AJAX call to get the information about the first planet that the film contains. Your function should return a promise that when resolved will console.log the name of the character and the film they are featured in and the name of the planet.

starWarsString(1).then(function(data){
    console.log(data)
})

// Output: "Luke Skywalker is featured in The Empire Strikes Back,
// directed by Irvin Kershner and it takes place on Hoth"

Object Rest

  • Gather remaining (rest) of keys and values in an object and create a new one out of them
In [18]:
var instructor = {first:"Elie", last:"Schoppik", job:"Instructor", numSiblings:3};
var { first, last, ...data } = instructor

first;
Out[18]:
'Elie'
In [19]:
last;
Out[19]:
'Schoppik'
In [20]:
data;
Out[20]:
{ job: 'Instructor', numSiblings: 3 }

Object Spread

  • Spread out keys and values from one object to another
  • Great for creating objects starting with default values and is a more concise alternative to Object.assign
In [22]:
var instructor = {first:"Elie", last:"Schoppik", job:"Instructor"};
var instructor2 = {...instructor, first:"Tim", last:"Garcia"}; //replace first and last
instructor2;
Out[22]:
{ first: 'Tim', last: 'Garcia', job: 'Instructor' }
In [25]:
var defaults = {job: "Instructor", ownsCat:true, ownsDog: true};
defaults;
Out[25]:
{ job: 'Instructor', ownsCat: true, ownsDog: true }
In [26]:
var matt = {...defaults, ownsCat: false};
matt;
Out[26]:
{ job: 'Instructor', ownsCat: false, ownsDog: true }
In [27]:
var colt = {...defaults, ownsDog: false};
colt;
Out[27]:
{ job: 'Instructor', ownsCat: true, ownsDog: false }