Index

ES6


ES2015 Cheatsheet


LESSONS from es6.io by Wes Bos


Basics
  const constVariableg = "string"; // can only be defined once. Global, and its value cannot be altered (unless it's an Object)
  let letVariable = "string"; // can only be declared once, but its value can be altered.
  var varVariable = "string"; // can be redefined at will.


09 - Default Function Arguments

Put default arguments and pass undefined as argument

    function becomeBetter(goal, average = 50, effort = 200) {...
    };
    becomeBetter(100, undefined, 50);


12 - Template Strings Introduction

Template literals

    var backticks = `My name is ${github}`;


13 - Creating HTML Fragments with template strings literals
  const developer = {
    name: "Cool Guy",
    age: 123,
    fun: true
  };

  const longString = `
    <div class="long">
      <span>${developer.name}</span>
      <p>${developer.age}</p>
    </div>
  `;

  const people = [
    {name: "Mike", age: 23},
    {name: "John", age: 43}
  ];

  const team = `
    <ul>
      ${people.map(person => `
          <li>${person.name} is ${person.age}</li>
        `).join("")}
    </ul>
  `;


14 - Tagged Template literals
  // strings ==  array of 'bio' substrings
  // ...values == array of variables name and age
  function wrapContent(strings, ...values) {
    let str = '';
    strings.forEach((string, i) => {
      str += `${string} <strong>${(values[i] || '')}</strong>`;
    });
    return str
  };

  const name = "Johnny";
  const age = 52;
  const bio = wrapContent`The dude's name is ${name}; he's ${age}`;


17 - New string methods
  let abc = "ABC"
  // .startsWith()
    abc.startsWith("A"); // true
    abc.startsWith("B", 1); // true
  // .endsWith()
    abc.endsWith("C"); // true
  // .includes()
    abc.includes("AB"); // true
  // .repeat()
    abc.repeat(2); // "ABCABC"


18 - Destructuring objects
  const france = {
    continent: "Europe",
    language: "French",
    sites: {
      castle: "Versailles"
    }
  };
  const { continent, language:lang } = france;
  const { castle } = france.sites;
  // yields `const castle`, `const continent` and `const lang`
  const settings = { width: 300, color: 'black' };  // height, fontSize
  const { width = 100, height = 100, color = 'blue', fontSize = 25} = settings;
  const { w: width = 500, h: height = 800 } = { w: 600 };


19 - Destructuring arrays
  const france = ["french", 60000000, "Europe", "Sarkozy", "Hollande", "Pompidou"];
  // const france = "french,60000000,Europe";
  const [language, population, continent, ...presidents] = france;


20 - Swapping variables with Destructuring
  let first = "first";
  let second = "second";
  [first, second] = [second, first];


21 - Destructuring Functions - Multiple returns and named defaults
  function convertCurrency(amount) {
    const converted = {
      USD: amount * 10,
      GBP: amount * 5,
      EUR: amount * 8
    };
    return converted;
  };
  const { USD, EUR } = convertCurrency(123);


22 - The for of loop
  // for OF yields the value, while IN yields the index
  const devs = ["john", "joe"];
  for (const dev of devs) {
    console.log(dev)
  }; // -> "john", "joe"


23 - The for of loop in action
  // `.entries` creates an iterable "array prototype"
    for (const [index, name] of devs.entries()) {
      console.log(`${name} is at index ${index}`)
    };
  // Read the arguments passed to the function
    function unkownArgumentsAmount() {
      console.log(arguments)
    };


25 - Array.from() and Array.of()

Takes something array-ish and makes it a true array You can apply a map immediately in the second argument

  const ps = document.querySelectorAll("p .exemple")
  const arrDivs = Array.from(ps, exemple => {
    return exemple.textContent;
  });

Array.of() makes an array with the arguments passed to it


26 - Array.find() and Array.findIndex()

.find()

    const group = [{"id": "1", "name": "me"}, {"id": "2", "name": "you"}];
    const person = group.find(person => person.name === "you");
    // Object {id: "2", name: "you"}

.findIndex()

    const personIndex = group.findIndex(person => person.name === "you");
    // 1


27 - Array.some() and Array.every()

Array.some() returns true if condition is met in array Array.every() returns true ONLY if condition is met on every item

  const ages = Array.from(19, 21, 32, 25, 59);
  const oldEnough = ages.every(age => age >= 21); // false
  const leaderInGroup = ages.some(age => age >= 21); // true


28 - Spread Operator Introduction
  const people = ["John", "Mary", "Jack"];
  const twins = ["John", "Mary", "Jack"];
  const everybody = [...people, ...twins];
  // Duplicate an array
  const newEverybody = [...everybody];


29 - Spread exercise
  const heading = document.querySelector('.jump');
  heading.innerHTML = sparanWrap(heading.textContent);
  function sparanWrap(word) {
    return [...word].map(letter => `<span>${letter}</span>`).join('');
  };


30 - More Spread exemples
  const comments = [
    {id: 1, content: "Hey"},
    {id: 2, content: "Bonjour"},
    {id: 3, content: "Hola"},
  ];
  const whereFrance = comments.findIndex(comment => comment.content === "Bonjour");
  const noFrance = [...comments.slice(0, whereFrance), ...comments.slice(whereFrance + 1)];
  console.log(noFrance)


31 - Spreading into a function
  const people = ["John", "Mary", "Jack"];
  const singer = ["Sinatra", "Goodnight Irene"];
  twins.push(...people);
  function singer(singerName, song) {
    console.log(`${singerName} sang ${song}`);
  };
  singer(...twins)


33 - Object Literal Upgrades

You can populate an object with variables without specifying their key names

    const firstName = "John";
    const lastName = "Doe";
    const person = { firstName, lastName } // Object {firstName: "John", lastName: "Doe"}
  // functions in Object
    const modal = {
      create(selector) {
        // use this
      },
      create: function(selector) {
        // instead of this
      }
    };

  // create keys on the fly
    const total = {
      [lastName]: lastName,
      [`${lastName}Classy`]: `de ${lastName}`
    };

  // 'zip' two arrays
    const firstSinger = ["Frank", "Mark"];
    const lastSinger = ["Sinatra", "Knopfler"];
    const singer = {
      [firstSinger.shift()]: lastSinger.shift(),
      [firstSinger.shift()]: lastSinger.shift(),
    }


34 - Promises
  const posts = fetch("http://some.api/url/get/items");
  posts.then(data => data.json)
       .then(data => { console.log(data) })
       .catch((err) => { console.log(err) })


35 - Building your own Promises
  const p = new Promise((resolve, reject) => {
    setTimeout(() => {
      reject(Error("This error is wrapped in an error Object"));
    }, 1000);
  });
  p.then("Hey").catch((error) => console.log(error));

  const op = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("It worked");
    }, 1000)
  });


36 - Chaining Promises + Flow control
  const posts = [
    { id: 1, author: "Hemingway" },
    { id: 2, author: "Whitman" }
  ];

  const authors = [
    { id: 1, origin: "US", first_name: "Ernest", last_name: "Hemingway" },
    { id: 2, origin: "US", first_name: "Walt", last_name: "Whitman" }
  ];

  function getPostById( id ) {
    return new Promise( ( resolve, reject ) = & gt; {
      const post = posts.find( ( post ) = & gt; post.id == id );
      if ( post ) {
        resolve( post );
      } else {
        reject( Error( "Post not found" ) );
      }
    } );
  };

  function incorporateAuthorInfo( post ) {
    return new Promise( ( resolve, reject ) = & gt; {
      const author = authors.find( ( author ) = & gt; author.last_name === post.author )
      if ( author ) {
        resolve( author );
      } else {
        reject( Error( "Author not found" ) );
      }
    } );
  };

  getPostById(2)
    .then(post => { return incorporateAuthorInfo(post) })
    .then(post => { console.log(post) })
    .catch(err => { console.log(err) })


filter and reduce
  const numbers = [3, 62, 234, 7, 23, 74, 23, 76, 92];
  const result = numbers.filter(number => number >= 70)
    .reduce((a, b) => {
      return a + b
    }, 0);

// Refactor functions to arrow functions
  const names = ['wes', 'kait', 'lux'];

  const fullNames = names.map(function(name) {
    return `${name} bos`;
  });

  const fullNames2 = names.map((name) => {
    return `${name} bos`;
  });

  const fullNames3 = names.map(name => {
    return `${name} bos`;
  });

  const fullNames4 = names.map(name => `${name} bos`);

  const fullNames5 = names.map(() => `cool bos`);

  const sayMyName = (name) => {
    alert(`Hello ${name}!`)
  }

  sayMyName('Wes');