Skip to content

Instantly share code, notes, and snippets.

@jaimelr
Created November 15, 2019 22:51
Show Gist options
  • Save jaimelr/7287cd60cd66cbabf2dd081a42127e21 to your computer and use it in GitHub Desktop.
Save jaimelr/7287cd60cd66cbabf2dd081a42127e21 to your computer and use it in GitHub Desktop.
Rapid ES6 Training

An ES6 compatibility chart

New ES6 Syntax

let, const and block scoping

  • let: Not hoisting, we make sure the variable exist before using it.
  • Block scoping: We can redefine a variable within a block and that variable will disappear outside the block.
  • const: When we use this keyword to define a variable we MUST initialize it.

With letand const, anything declared inside the block STAYS in the block.

Arrow functions

() => {}

  • With 1 argument we can avoid parenthesis: arg => {}
  • return keyword is mandatory when using a block {}

The real purpose of arrow functions is to handle the this keyword.

  • ES5: On events this get set to the element that receives the event.
  • ES6: On events this refers to the context of the code run.

Object Literal

var objectLiteral = {
  name: 'value',
  another_name: func () {}
}
  • ES5: In object literals with the function keyword this is set to the object on which the function is called.

  • ES6: In object literals with arrow functions this is set to the context where the code runs.

  • You can't bind a new object to an arrow function

  • We are not going to be able to change the value of this thus call, bind and apply are useless.

  • We do not have access to the prototype field in arrow functions.

  • When declaring default parameters we have access to variables within the scope.

  • It is not a good practice the use of arguments

Rest and Spread ...

Rest

Refers to gathering up parameters and putting them all into a single array.

const myFunc = (p1, ...categories) => {} // Where categories [2, 3]
myFunc(1, 2, 3)

Spread

Refers to splitting out the elements of an array or even a string.

  • Takes an array and coverts it into a list of params (opposite of Rest)

JS allows trailing commas [1, 2, 3,]

Spread splits a string into its individual caracters.

Object literal extensions

  • Withing object literals:
{ price: price } -> { price }
  • We no longer need to specify the function key
{ myFunc() {} }
  • We can use a variable name as a field
  • We can put an entire expression within brackets
{ var p1 = { ['foo' + 'bar']: 'test' } }

For ... of loops

var arr = ['foo', 'bar'];
for (var item of arr) {
  console.log(item)
}

Loops through each item in the array.

Template Literals

Invoice Number: ${testVar}

  • By splitting the $ with \$ no interpolation takes place.
  • New lines and spaces are respected.

Destructuring

let salary = ['32', '566', '1'];
let [low, high, min] = salary;
  • We can pull nested values
  • We can add defaults
  • We can skip element but adding an extra comma
  • We can destruct in function params
  • We use {} to destruct objects
  • We need to make sure property names match variable names when destructuring objects
  • Requires an enumerator

ES6 Modules and Classes

Modules

Simple by loading a module it gets executed once

  • Modules run in strict mode
  • import and export communicate modules
  • We can export as many values as we want
  • You can us as to assign an import
  • An import statement gets hoisted
  • Without {} in the import statement the module loader looks for the default export
  • One default per export
  • If there's no default export the default import assigns undefined
  • When we import everything with the * char we need to give an alias

Named Exports in Modules

  • Imports are read-only
  • As an object we are free to modify its properties

Class Fundamentals

  • class Task: typeof Task -> function
  • There´s no need to use the function keyword when declaring function in a class
  • We have constructor in classes
  • The class body is not a place to declare variables
  • Classes are not hoisted
  • We can't call the call function to change the this object
  • Classes are not in the window object

extends and super

class Project {}
class SoftwareProject extends Project {}
  • If the previous class is going to have a constructor it needs to call super
  • You can use super in object literals
  • We always use the this keyword when initializing variables in the constructor

Static members

  • By using the static keyword the method gets attached to the class as a constructor function
  • We can only have static methods

new.target

  • Mainly use in the constructor
  • Is a function pointing to the constructor
  • It's always going to point to the first constructor that called it
  • It's useful to refer back to the original class that is getting created

New Types and Object Extensions

Symbols

The purpose of a symbol is to generate a unique identifier Symbol()

  • New type in ES6
  • Well-known symbols: toStringTag, isConcatSpreadable, toPrimitive
  • Used for metaprogramming

Object extensions

  • Object.assign
  • setPrototypeOf
  • Properties are enumerable by default
  • Object.is Compare variables

String Extensions

  • startsWith()
  • endsWith()
  • includes()
  • \u{}

Number Extensions

Prefer the use of Number.parseInt instead of parseInt. We try to avoid global functions

  • Some global functions convert strings to values like Number and Nan
  • isSafeInteger()
  • Number.EPSILON
  • Number.MAX_SAFE_INTEGER

Math Extensions

  • sign()
  • trunc()

RegEx Extensions

  • /.../u <- For testing unicode

Function Extensions

Function.name isn't writable but is configurable with Object.defineProperty

Iterators, Generators, and Promises

Iterators

  • When we reach the end of the array we get an object { done: true, value: undefined }
  • We use next() as the main function in an iterator

Generators

We use generators to call iterators multiple times

function *gen() {
  yield;
}
  • When we run a generator the result is an iterator
  • .throw finishes the iterator

Promises

A promise is an object that is waiting for an asynchronous operation to complete. When the operation does complete the promise is either fulfilled or rejected

  • resolve()
  • reject()

Arrays and Collections

Array Extension

  • Array.of(9000) New way to create an array
  • Array.from(values, () => {})
  • [].fill() Fills the entire array with 1 value, accepts: value, start, end (not inclusive)
  • [].find(() => {}) Receives a lambda. As soon as it finds a match it returns
  • [].copyWithin() Accepts: destination and source
  • [].keys() Get the indexes
  • [].values() Get the values

Map and WeakMap

These are useful when you have some kind of object you need to key the map of of

  • Map(): .set(), .get(), .size(), .size(), .delete(), .clear(), .has(), .values(), .entries()

Set and WeakSet

Similar to Map and WeakMap except that they deal with single values

  • Set(): .add(), .seize(), .has()
  • Items are unique
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment