Skip to content

Instantly share code, notes, and snippets.

@zbeyens
Forked from vasco3/es6-cheatsheet.markdown
Last active February 27, 2018 03:14
Show Gist options
  • Save zbeyens/1328c5976a628f1c531ea4710c96805e to your computer and use it in GitHub Desktop.
Save zbeyens/1328c5976a628f1c531ea4710c96805e to your computer and use it in GitHub Desktop.
ES6 cheatsheet

Table of Contents generated with DocToc

FrontEnd Masters - ES6 notes

Slides

  • ECMAScript is now EcmaScript. Which is a standard for the API JavaScript and other languages use.
  • TC39 stands for Technical Committee which regulate the EcmaScript API.
  • ES.Next is a pointer to the next version of ES
  • ES Harmony is the backlog of the new stuff coming to ES and the versions in development.

Function Hoisting

// Function Declaration
function foo() {
  // code here
}
// Function Expression
var bar = function() {
  // code here
}

Function declaration gets hoisted to the top, while Function Expression does not.

Variables

  • var: gets hoisted
  • let: lives within block (curly braces)
  • const: constant.. also lives within blocks

Temporal Dead Zone

function doSomething() {
  console.log(a); // should cause an error
  let a = 1;
  console.log(a);
}

Spread Operator

Spreads an array into its individual values.

var a = [1, 2];
var b = returnTwo(a[0], a[1]); // [2, 1]
var c = returnTwo(...a); // [2, 1]

concat arrays with spread

let nums = [1, 2, 3];
let abcs = ['a', 'b', 'c'];

let alphanum = [ ...nums, ...abs ]; // [1, 2, 3, 'a', 'b', 'c']

Object short-hand

const x = 4;
const y = 2;

const o = { x, y, z: x * y }; // { x: 4, y: 2, z: 8 }

Descructuring

"Destructuring allows you to bind a set of variables to a corresponding set of values anywhere that you can normally bind a value to a single variable."

It helps pull incoming objects apart.

var address = {
  city: "Costa Mesa",
  state: "CA",
  zip: 92444
};
let {city, state, zip} = address;

log(city); // 'Costa Mesa'
log(state); // 'CA'
log(zip); // 92442

Alias

or we can use alias

var address = {
  city: "Costa Mesa",
  state: "CA",
  zip: 92444
};
let {city: c, state: s, zip: z} = address;

log(c, s, z); // 'Costa Mesa CA 92444'

Simpler way

You can also use it like

var person = {name: 'Aaron', age: 35};
displayPerson(person);

function displayPerson({name, age}) {
  // do something with name and age to display them
}

Default values

You can pass default values

var person = {name: 'Aaron', age: 35};
displayPerson(person);

function displayPerson({name = "No Name provided", age = 0}) {
  // do something with name and age to display them
}

Destructuring Arrays

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

var [first, second,,,,fifth] = nums;
log(first, second, fifth); // 1, 2, 5

Swapping variables

how to swap variables without using a temp var

var a = 1, b = 2;

// The Old Way
var temp = a, a = b, b = tmep;

// The New Way
[b, a] = [a, b];

Arrow Functions

They can't be use with new because of how they bind this.

var fn1 = function() {return 2;};
var fn2 = () => 2; // Here you can omit curly braces. It means return 2. If you add curly braces then you have to put the word 'return'.

Parenthesis-Parameter Rules

var x;
x = () => {};       // No parameters, MUST HAVE PARENS
x = (val) => {};    // One parameter w/ parens, OPTIONAL
x = val => {};      // One parameter w/o parens, OPTIONAL
x = (y, z) => {};   // Two or more parameters, MUST HAVE PARENS
x = y, z => {};     // Syntax Error: must wrap with parens when using multiple params

REAL benefit: lexical binding of 'this'

You don't need to bind(this) or var _this = this.

var widget = {
  init: function() {
    document.addEventListener("click", (event) => {
      this.doSomething(event.type);
    }, false);
  },
  doSomething: function(type) {
    console.log("Handling " + type + " event");
  }
};
Widget.init();

You can't replace all functions with Arrow functions because it will mess up this.

Classes

var monsterHealth = Symbol(); // Symbol() is a JS method that acts like a GUID generator
var monsterSpeed = Symbol();

class Monster {
  constructor(name, health, speed) {
    this.name = name;
    this[monsterHealth] = health;
    this[monsterSpeed] = speed;
  }
  // getter
  get isAlive() {
    return this[monsterHealth] > 0;
  }
  // setter
  set isAlive(alive) {
    if(!alive) this[monsterHealth] = 0;
  }
  // method
  attack(target) {
    console.log(this.name + ' attacks ' + target.name);
  }
}

var Jorge = new Monster('Jorge', 3);
Jorge.isAlive; // true   

jorge.isAlive = false;
console.log(jorge.isAlive); // false

Extend classes

class Godzilla extends Monster {
    constructor() {
        super('Godzilla', 10000);
    }
    
    attack(target) {
      super(target); // will call the Monster attack method
    }
}

Modules

Like CommonJS

Default export

The default means will import the default export.

// MyClass.js
class MyClass{
  constructor() {}
}
export default MyClass;

// Main.js
import MyClass from 'MyClass';

Multiple exports.

You can call just the exports you need from a specific module.

// lib.js
export const sqrt = Math.sqrt;
export function square(x) {
  return x * x;
}
export function diag(x, y) {
  return sqrt(square(x) + square(y));
}

// main.js
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5

// second.js
// or you can call them with '*'
// but then you have to prefix the exports with
// the module name

import * as lib from 'lib';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5

More info

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment