Getting Started with ES6 and ES7 JavaScript

ES6 and ES7 Intro Image

Class 3

Today's Topics

  1. Review at-home challenges from last class
  2. Function Parameters
  3. Object Syntax
  4. Destructuring Objects
  5. Destructuring Arrays

Review: Implement a reject function

Answer: Use the filter() array helper.
View Solution »
function reject(array, iteratorFunction) {
  // your code here
}

Hint: You may use filter.

Fork this CodePen for some starter code.

Reject should work opposite to filter; if a function returns true, the item should not be included in the new array, for example:
 

const numbers = [ 5, 10, 15, 17, 18, 20 ];
const lessThanEighteen = reject(numbers, number => number >= 18);
console.log(lessThanEighteen);
// returns [ 5, 10, 15, 17 ];

Review: Implement a reject function

Review: Implement a pluck function

Answer: Use the map() array helper.
View Solution »
function pluck(array, property) {
  // your code here
}

Hint: Access a property on an object by using square bracket notation. For example:
 

const animal = { type: 'Dinosaur', status: 'Extinct' };
animal['type']; // returns 'Dinosaur'

Pluck should accept an array and a string representing a property name and return an array containing that property from each object, for example:
 

const cats = [ { name: 'Colonel Meow' }, { name: 'Lil Bub' }, { name: 'Grumpy Cat' }];

pluck(cats, 'name');
// returns ['Colonel Meow', 'Lil Bub', 'Grumpy Cat'];

Review: Implement a pluck function

pluck Function

Review: Write a findWhere function

Answer: Use the find() array helper with Object.keys().
View Solution

Often we need to find an object with a given property and value. Write a findWhere function that accepts two parameters, the array and the criteria as an object, and returns the matching object. You may assume that the criteria is one key-value pair. Fork this CodePen for some starter code.

Hint: Use Object.keys(criteria)[0] to figure out the name of the property on the object. For example, Object.keys({ type: 'marsupial' }) would return 'type'. You could then check to see if a given element in the array had a property equal to the criteria's value with something like element[property] === criteria[property].

The following code ...

const animals = [
  { id: 0, name: 'iguana', type: 'reptile' },
  { id: 1, name: 'cardinal', type: 'bird' },
  { id: 2, name: 'platypus', type: 'marsupial' },
  { id: 3, name: 'frog', type: 'amphibian' }
];

findWhere(animals, { type: 'marsupial' });

would return one object ...

{ id: 2, name: 'platypus', type: 'marsupial' }

At-Home Challenge: Write a filterWhere function

Write a filterWhere function that accepts two parameters, the array and the criteria as an object, and returns an array of matching objects. All of the criteria must match for an object to be included in the resulting array. Assume that multiple criteria can be included, for example:

filterWhere(animals, { name: 'kangaroo', type: 'marsupial' })

Fork this CodePen for some starter code.

Hint: Although you may need different array helpers for this challenge, we recommend warming up with the previous slide's findWhere challenge first.

The following code ...

const animals = [
  { id: 0, name: 'iguana', type: 'reptile' },
  { id: 1, name: 'cardinal', type: 'bird' },
  { id: 2, name: 'platypus', type: 'marsupial' },
  { id: 3, name: 'kangaroo', type: 'marsupial' },
  { id: 4, name: 'frog', type: 'amphibian' }
];

filterWhere(animals, { type: 'marsupial' });

would return an array of ...

[
  { id: 2, name: 'platypus', type: 'marsupial' },
  { id: 3, name: 'kangaroo', type: 'marsupial' }
]
View Solution

At-Home Challenge: Implement a unique function

function unique(array) {
  // your code here
}

Hint: Use reduce and find.

Write a function that will remove duplicate values from an array. For example:
 

const arr = [ 5, 5, 10, 10, 15, 20, 20 ];
const uniqueArr = unique(arr);
console.log(uniqueArr);
// returns [ 5, 10, 15, 20 ];
View Solution

At-Home Challenge: Implement a unique function

Create a unique() function with reduce and find

Function Parameters

Default Parameter Values

Using ES5, we could establish default parameter values, but there were some flaws
View CodePen »

ES5:

function makeRequest(url, timeout, callback) {
  timeout = timeout || 2000; // what if timeout is 0?
  callback = callback || function() {};
  callback();
}

becomes

function makeRequest(url, timeout, callback) {
  timeout = (typeof timeout !== 'undefined') ? timeout : 2000;
  callback = (typeof callback !== 'undefined') ? callback || function() {};
  callback();
}

ES6:

function makeRequest(url, timeout = 2000, callback = () => {}) {
  callback();
}
It's beautiful

It's beautiful

Calling functions with default parameters

Given the following function:

function makeRequest(url, timeout = 2000, callback = () => {}) {
  callback();
}

Only url is required. The following calls all work:

makeRequest('/api');

makeRequest('/api', 500);

makeRequest('/api', 0, requestData => updateDatabase(requestData));

makeRequest('/api', undefined, requestData => updateDatabase(requestData));

Enforcing mandatory parameters

Since default values are only evaluated when used, use it to enforce that a certain parameter is provided:

function mandatory() {
  throw new Error('You forgot a parameter!');
}

function doSomething(mustBeProvided = mandatory()) {
  return mustBeProvided;
}

Activity

Using default parameters

See the Pen Default parameters activity by Liz Shaw (@anythingcodes) on CodePen.

View Solution

Rest Parameters

Placing ... before a function parameter transforms that parameter and the rest (i.e. all following parameters) into an array

function giveItARest(param1, ...allTheRest) {
  console.log(param1);
  console.log(allTheRest);
}

giveItARest(1, 2, 3, 4, 5, 6);
// 1
// [2, 3, 4, 5, 6]

Useful when you don't know how many arguments will be passed to a function

Activity

Using rest parameters

See the Pen Rest parameter activity by Liz Shaw (@anythingcodes) on CodePen.

View Solution

Spread operator

Placing ... before an array spreads the array into its individual elements

const numbers = [2, 3, 4];
const numbers = [2, 3, 4];

console.log([1, numbers]);
const numbers = [2, 3, 4];

console.log([1, numbers]); // nested array: [1, [2, 3, 4]]
const numbers = [2, 3, 4];

console.log([1, numbers]); // nested array: [1, [2, 3, 4]]

console.log([1, ...numbers]);
const numbers = [2, 3, 4];

console.log([1, numbers]); // nested array: [1, [2, 3, 4]]

console.log([1, ...numbers]); // normal array: [1, 2, 3, 4]

Rest vs. Spread

...

Rest parameters, primarily used in function parameters, to transform individual elements into an array

function sum(first, ...others) {
  // others will be an array here
}

Spread operator used on an array to transform the array into individual elements

const arr1 = ['a', 'b', 'c'];
const arr2 = ['x', 'y', 'z'];
const combo = [...arr1, ...arr2];
console.log(combo); // ['a', 'b', 'c', 'x', 'y', 'z']

Activity

Using the spread operator and rest parameters

Activity 1

See the Pen Spread Operator Activity by Liz Shaw (@anythingcodes) on CodePen.

View Solution »

Activity 2

See the Pen Spread and Rest Activity by Liz Shaw (@anythingcodes) on CodePen.

View Solution »

Object Syntax

Property Initializer Shorthand

When an object property name is the same as the local variable name, you can include the name without a colon and value

ES5:

function saveData(url, data){
  $.ajax({ method: 'POST', url: url, data: data });
}

becomes

ES6:

function saveData(url, data){
  $.ajax({ url, data, method: 'POST' });
}

Sometimes referred to as enhanced literal notation

Concise methods

Object methods no longer need : function

ES5:

var dog = {
  name: 'Boo',
  bark: function() {
    console.log('yip!');
  }
};
dog.bark(); // yip!

becomes

ES6:

const dog = {
  name: 'Boo',
  bark() {
    console.log('yip!');
  }
};
dog.bark(); // yip!

Activity

Using Enhanced Object Syntax

See the Pen Object Syntax by Liz Shaw (@anythingcodes) on CodePen.

View Solution

Destructuring Objects

Destructuring Objects

Unpack properties from objects into distinct variables

ES5:

var person = {
  name: 'Whitney',
  age: 38
};

var name = person.name;
var age = person.age;

console.log(name, age);
// Whitney 38

becomes

ES6:

const person = {
  name: 'Whitney',
  age: 38
};

const { name, age } = person;
console.log(name, age);
// Whitney 38
  • Left-hand side of the equal sign (=)
    A comma-separated list of the object's keys you'd like to unpack, wrapped in { }
  • Right-hand side of the equal sign (=)
    The object you're destructuring

Activity

Using Object Destructuring

See the Pen Object Destructuring Activity 1 by Liz Shaw (@anythingcodes) on CodePen.

View Solution

Default Values

What if an object doesn't contain a key with that name?

Set a default value with equal signs (=)

ES5:

var person = {
  name: 'Whitney'
};

var name = person.name;
var active = person.active; // undefined

console.log(name, active);
// Whitney undefined

becomes

ES6:

const person = {
  name: 'Whitney'
};

const { name, active = false } = person;
console.log(name, active);
// Whitney false

Destructuring in Function Parameters

Destructuring is often used in function parameters

 

const user = {
  username: 'TheGreatCatsby',
  password: 'catlord',
  email: 'catsby@catfancy.com',
  dateOfBirth: '04/26/1984',
  city: 'Boston'
};





                
const user = {
  username: 'TheGreatCatsby',
  password: 'catlord',
  email: 'catsby@catfancy.com',
  dateOfBirth: '04/26/1984',
  city: 'Boston'
};

function register( { email, username, password, dateOfBirth, city }) {
  // code to create a new user
}
const user = {
  username: 'TheGreatCatsby',
  password: 'catlord',
  email: 'catsby@catfancy.com',
  dateOfBirth: '04/26/1984',
  city: 'Boston'
};

function register( { email, username, password, dateOfBirth, city }) {
  // code to create a new user
}

register(user); // will be destructured within register() parameters

Activity

Using Object Destructuring in Function Parameters

See the Pen Activity: Object Destructuring by Liz Shaw (@anythingcodes) on CodePen.

View Solution

Assigning to Different Local Variable Names

What if you want to use a different name for your destructured variables?

const { name, age } = person;
const { name, age } = person;
const localName = name;
// localName is the variable name I want to use going forward

 

  1. Use a : in the comma-separated list of keys
  2. The variable name after : can now be referenced as a local variable

 

const { name : localName, age } = person;
// now I can reference localName going forward!

Destructuring Arrays

Destructuring Arrays

Array destructuring operates on positions within an array rather than any named properties

ES5:

var colors = ['red', 'green', 'blue'];

var first = colors[0];
var second = colors[1];
var third = colors[2];

console.log(first, second, third);
// red green blue

becomes

ES6:

const colors = ['red', 'green', 'blue'];

const [ first, second, third ] = colors;

console.log(first, second, third);
// red green blue
  • Left-hand side of the equal sign (=)
    A comma-separated list of the values you'd like to unpack, wrapped in []
  • Right-hand side of the equal sign (=)
    The array you're destructuring

Default Values

What if an array doesn't contain a value at that index?

Set a default value with an equal sign (=)

ES5:

var scores = [ 94, 89 ];

var first = scores[0];
var second = scores[1];
var third = scores[2] === undefined ? 0 : scores[2];

console.log(first, second, third); // 94 89 0

becomes

ES6:

const scores = [ 94, 89 ];

const [ first, second, third = 0 ] = scores;

console.log(first, second, third); // 94 89 0

Swapping Variables with Destructuring

Often you need to swap the values of two variables (especially in sorting algorithms). Use array destructuring to make it happen!

ES5:

var a = 1;
var b = 2;
var temp = a;

a = b;
b = temp;

console.log(a); // 2
console.log(b); // 1

becomes

ES6:

let a = 1;
let b = 2;

[ a, b ] = [ b, a ];

console.log(a); // 2
console.log(b); // 1

🌟 No need to create a temporary variable!

Activity

Using Array Destructuring

See the Pen Array Destructuring - Converting to Object - Activity by Liz Shaw (@anythingcodes) on CodePen.

View Solution

At-Home Challenge

Refactor a detectCollision function

Although detectCollision works as intended, we can refactor it to improve its performance and readability. Reformat detectCollision to use destructuring and an array helper.

Hint: We'll return a single matched object. Which array helper would be best in this case?

View Solution »

At-Home Challenge

Mixed Destructuring

const node = {
  location: {
    start: {
      line: 1,
      column: 1
    },
    end: {
      line: 1,
      column: 4
    }
  },
  range: [0, 3]
};

const {
  location: { start },
  range: [ index ]
} = node;

console.log(start.line);
console.log(start.column);
console.log(index);

What would the following output to the console and why?

Questions

?