Skip to content

Instantly share code, notes, and snippets.

@davidcalhoun
Last active August 30, 2018 13:10
Show Gist options
  • Save davidcalhoun/65e84230596c5ad1fa538cac55a488d2 to your computer and use it in GitHub Desktop.
Save davidcalhoun/65e84230596c5ad1fa538cac55a488d2 to your computer and use it in GitHub Desktop.
ES6 cheatsheet

From Learncode YouTube: Part 1, Part 2

Transpile to ES5

  • babeljs.io - most mainstream
  • Traceur - competitor

Destructuring

Destructuring: Objects

var foo = {
  bar: 1,
  baz: 2
};

// Old way
var bar = foo.bar;
var baz = foo.baz;

// New way
var {bar, baz} = foo;

Destructuring: Arrays

var tenses = ["me", "you", "he"];

// Old way
var firstPerson = tenses[0];
var secondPerson = tenses[1];

// New way
var [ firstPerson, secondPerson ] = tenses;

Tip: Leave spaces around { } and [ ] to give visual cue that it's destructuring.

Destructuring: Arrays example with Promise.all

// Old way
Promise.all([promise1, promise2]).then(results) {
  var results1 = results[0];
  var results2 = results[1];
  
  console.log(results1, results2);
}

// New way
Promise.all([promise1, promise2]).then([ results1, results2 ]) {
  console.log(results1, results2);
}

Destructuring: Object creation

var bar = 2;

// Old way
var obj = {
  foo: 1,
  bar: bar
};

// New way
var obj = {
  foo: 1,
  bar
};

Destructuring: temporary object creation for passing data to functions

var name = "dave";
var age = 92;

// Old way
some.method({
  name: name,
  age: age
});

// New way
some.method({ name, age });

Objects: dynamic keys

Note: Not as commonly used

var name = "dave";

// Old way -  two-step process
var obj = {};
obj["name" + name] = "some value";

// New way
var obj = {
  ["name" + name]: "some value"
};

Destructuring arguments

Very useful

Old way

This old pattern used an options object when the number of arguments got too long, so we didn't have to worry about the exact order in which variables were passed in:

function calculateBmi(opts){};

calculateBmi({
  weight: 220,
  height: 183,
  max: 25,
  callback: function() {}
});

New way

function calculateBmi(weight, height, max, callback) {
  // code here
};

const weight = 220;
const height = 183;

// order doesn't matter here!
calcBmi({ max: 25, height, weight });

// we can leave out max here without passing in null!
calcBmi({ weight, height, callback: function(){} } );

Default args

// Old way
function calcBmi(max) {
  if (typeof max === 'undefined') max = 25;
};

// New way
function calcBmi({ max = 25 }){

};

Renaming args

// Old way
function calcBmi(opts) {
  var h = opts.height;
  console.log(h);
};

function calcBmi({ height: h }){
  console.log(h);
};

Template strings

Very useful, often used.

var name = "dave";
var action "take photos";

// Old way
var singleLineGreet = "hi, my name is " + name + " and I like to " + action + ".";

var multilineGreet = "hi, my name is\n" +
                     name +
                     "and I like to\n" +
                     action;

// New way - with template variables and backtics
var singleLineGreet = `hi, my name is ${name} and I like to ${action}`;

var multilineGreet = `hi, my name is ${name}
and I like to
${action}`;

Note: Atom editor has better default ES6 syntax highlighting compared to Sublime

Block scoping with let

Basically, let/const is the new var. var is becoming less used now because variables created with it can be modified in sometimes unexpected ways, especially when developers are new to JS.

Old way

if (true) {
  var b = 2;
};
console.log(b);  // 2

This can be problematic because the variable b is NOT self-encapsulated to this code block (in braces). Instead, it's hoisted outside of the block. This is why b is accessible following the code block, when it's outputted to the console.

This is problematic because the variable b can be accessed and modified outside of its code block, which is what we want to avoid if possible.

New way

if (true) {
  let b = 2;
};
console.log(b); // Uncaught ReferenceError: b is not defined

This is better because b is not accessible outside of this scope block, and is therefore self-encapsulated. This leads to no side-effects if other code blocks try to reuse this variable name.

Note that we can also use let inside for for and while loops.

Block scoping with const

const is block-scoped just like let, but it cannot be overwritten later:

const foo = 1;
foo = 2;  // Uncaught TypeError: Assignment to constant variable.

Note that objects created with const can still be mutated however, which might be confusing:

const obj = {
  foo: 1
};
obj.foo = 2;  // this works fine!

Use const for everything where possible, as you should be writing code that in this more purely functional way, leading to less side effects. If you do need to change the value of something later, use let.

Classes

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