ES6 All The Things

Collection of ES6 goodies for next-level dev 🤓💻

Follow  Star

New Variables

const with primitive values

Block-scoped. Cannot be re-assigned. Primitive values are immutable.
const test = 'test';

const with reference values

Block-scoped. Cannot be re-assigned. Reference values are mutable.
const test = { message: 'Hello World' };
test.message = 'Goodbye World';

let

Block-scoped. Can be re-assigned.
let i = 0;

Promises

Promises

A promise represents the eventual result of an asynchronous operation. It can be pending (neither fulfilled nor rejected), fulfilled (operation completed successfully), or rejected (operation failed). If either fulfilled or rejected, the associated handlers from a promise's then method are called.
// Creating the promise
const p = new Promise(function(resolve, reject) {
 if (/* condition */) {
  resolve(/* value */);
  } else { 
  reject(/* reason */) 
 }
}); 

// Consuming the promise
p
 .then((data) => console.log(data))
 .catch((err) => console.log(err));

Functions

Arrow Functions

Cannot be named. Doesn't re-bind the value of this. If there's only one parameter the parentheses can be left off. If the callback is a one-liner (only returning something) you can do implicit return, however, if the return is an object literal, you must wrap in parentheses.
const arrow = (dart, bow) => console.log('Implicit return');
const arrow = dart => console.log('One parameter');
const arrow = () => console.log('No parameters');
const arrow = () => ({ foo: 'bar' }); // Returns an object literal

Default Function Arguments

Sets the default argument if nothing is passed in.
function multiply(a, b = 1) {
 return a * b;
}

console.log(multiply(5));
// 5
console.log(multiply(5, 3));
// 15

Template Strings

Template Strings

Interpolates variables inside of strings with backticks and brackets.
const name = 'Melanie';
console.log(`Hello, ${name}!`);
// Hello, Melanie!

Tagged Template Literals

Tags allow you to parse template literals with a function. You’ll get access to all the string values as the first argument (in an array), and the interpolated expression(s) as the second argument. If the amount of expressions are unknown, ...rest can be used. The styled-components package utilizes TTL.
const name = 'Melanie';
const messages = 5;

function hello(strings, ...values) {
 console.log('Strings:', strings);
 console.log('Values:' values);
}

const welcome = hello`Hello, ${name}! You have ${messages} new messages.`
// Strings: ['Hello, ', '! You have ', ' new messages.']
// Values: ['Melanie', '5']

Array Methods

Array.from() and Array.of()

Array.from takes something that is array-ish and turns it into a true array. Array.of creates an array from every single argument passed to it.
// Array.from
const navItems = document.querySelectorAll('.nav li');
const navItemsArray = Array.from(navItems);

// Array.of
const ages = Array.of(5, 15, 20, 3);

Array.find() and Array.findIndex()

Array.find returns the value of the first element that satisfies x condition. Array.findIndex returns the index of the first element that satisfies x condition.
const ids = [5, 45, 30];

// Array.find
const find = ids.find(x => x <= 10);
console.log(find);
// 5

// Array.findIndex
const find = ids.findIndex(x => x >= 40);
console.log(find);
// 1

String Methods

startsWith(), endsWith(), includes(), repeat()

Determines if a string starts with/ends with/includes specified character(s). Can skip characters if needed. Case sensitive. Also, repeat a string x number of times.
const str = 'Coding is awesome';

console.log(str.startsWith('C'));
// Returns true

console.log(str.endsWith('a', 6));
// Returns false

console.log(str.includes('awe'));
// Returns true

const rock = '🚀';
console.log(rock.repeat(10));
// 🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀

Destructuring

Objects

Allows properties of objects to be extracted into their own variables. You can also assign the props to a different name upon destructuring.
const obj = { title: 'Dr', name: 'McDreamy'};
function giveLove({ title, name }) {
 console.log(`${title} ${name} is sexy`);
}
console.log(giveLove(obj));
// Dr McDreamy is sexy

// Renaming props
const user = { theName: 'Melanie' };
const { theName: name } = user;
console.log(name);
// Melanie

Nested Objects

Nested objects can also be destructured.
let user = {
 education: {
  degree: {
   name: 'Bachelor',
   field: 'Multimedia'
  },
  country: 'Australia'
 }
};

let {
 education: {
  degree: {
   name,
   field 
  },
  country
 }
} = user;

console.log(`Studied ${name} of ${field} in ${country}`);
// Studied Bachelor of Multimedia in Australia

Arrays

Allows array index values to be extracted into their own variables. You can ignore values that you're not interested in.
const arr = ['Melanie', 1337];

const [name, coolness] = arr;
console.log(`${name} is ${coolness} 😎`);
// Melanie is 1337 😎

// Ignore values
const [, coolness] = arr;
console.log(coolness);
// 1337

Swapping Variables

Creates an array of [x, x] and immediately destructure into the opposite.
console.log(player, benched); // Steve, John
[player, benched] = [benched, player];
console.log(player, benched); // John, Steve

Iterables and Loops

for of

Can be used for any type of data except objects. Able to use break and continue.
for (const item of items) {
 console.log(item);
}

Operators and Parameters

...spread

Takes every single item from an iterable and expands it.
const people = ['Sara', 'John'];
const cats = ['Callie'];
const myFamily = [...people, ...cats];
console.log(myFamily);
// myFamily is ['Sara', 'John', 'Callie']

...rest

Represents an indefinite number of arguments as an array. Used in functions and destructuring.
function multiply(rate, ...numbers) {
 return numbers.map(number => number * rate);
}

console.log(multiply(2, 10, 20, 30));
// 20, 40, 60

Global Objects

Map, Map.set(), Map.get(), Map.size()

Map, not to be confused with Array.prototype.map(), holds key-value pairs. While Map's and object-literals have their similarities, they also have some key differences.
const myMap = new Map(); // creates a new instance of a Map object
const keyObj = {};

console.log(myMap); // Map(0) {}

// unlike object-literals, a Map's keys/values can be anything
myMap.set('string', 'they can be strings')
myMap.set(1, 'or integers')
myMap.set(true, '...booleans')
myMap.set(keyObj, 'even objects?')

console.log(myMap.size) // 4

myMap.get(keyObj) // "even objects?"