Skip to content

Instantly share code, notes, and snippets.

@thedanotto
Last active November 5, 2018 19:40
Show Gist options
  • Save thedanotto/a3a993f1aa61308e7870a5c27ae0e0ff to your computer and use it in GitHub Desktop.
Save thedanotto/a3a993f1aa61308e7870a5c27ae0e0ff to your computer and use it in GitHub Desktop.
es6 cheatsheet

Fat Arrow

function definition

let timesTwo = params => params * 2

// or

let timesTwo = params => {
  return params * 2;
}

console.log(timesTwo(4));
  => 8

no binding of this needed, automatically uses this of where the function is defined

let obj = {
  id: 42,
  counter: function counter() {
    setTimeout(() => {
      console.log(this.id);
    }, 1000);
  }
};

Spread Operator

spread operator for args

var arr = [2, 4, 8, 6, 0];
var max = Math.max(...arr);

console.log(max);
  => 8

copy array without mutating the original array

var arr = ['a', 'b', 'c'];
var arr2 = [...arr];
arr2.push('d');

console.log(arr);
  => ['a', 'b', 'c']

console.log(arr2);
  => ['a', 'b', 'c', 'd']

Combine two arrays

var mid = [3, 4];
var arr = [1, 2, ...mid, 5, 6];

console.log(arr);
  => [1, 2, 3, 4, 5, 6]

Remove attr from object

let song = { artist: 'Coolio', length: 210, title: 'gangsta\'s paradise' }
const { artist, ...rest } = song;

console.log(artist);
  => 'Coolio'
  
console.log(rest);
  => { length: 210, title: 'gangsta\'s paradise' }
  
const songPlays = { ...rest, playCount: 0 };

console.log(songPlays);
  => { length: 210, title: 'gangsta\'s paradise', playCount: 0 }

Object Destructuring

const obj = { first: 'Jane', last: 'Doe' };
const { first, last } = obj;

console.log(first);
  => 'Jane'

console.log(last);
  => 'Doe'

Class Definition

class Foo {
    constructor(x) {
        this.x = x;
        this.y = 432;
    }

    point() {
        return 'Foo(' + this.x + ', ' + this.y + ')';
    }
}

let myfoo = new Foo(99);
console.log(myfoo.point()); // prints "Foo(99, 432)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment