Skip to content

Instantly share code, notes, and snippets.

@jessejlt
Created July 2, 2013 06:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jessejlt/5907112 to your computer and use it in GitHub Desktop.
Save jessejlt/5907112 to your computer and use it in GitHub Desktop.
Some ECMAScript 6 features I'm excited about

parameter default values

function func(a, b=1) {
  
}

named parameters

function func(arg, {opt1, opt2=4}) {
  
}

func(1, {2})

block-scoped variables

function func() {
  console.log(tmp); // undefined
  if (1) {
    var tmp = 1;
  }
}

function func() {
  console.log(tmp); // reference error
  if (1) {
    let tmp = 1;
  }
}

arrow functions

let squares = [1, 2, 3].map(function (x) {
  return x * x;
});

let squares = [1, 2, 3].map(x => x * x);

lexical this

function func(response) {
  var that = this;
  response.on('data', function (chunk) {
    that.onChunk(chunk);
  });
}

function func(response) {
  response.on('data', chunk => {
    this.onChunk(chunk);
  });
}

spread operator

similar to using apply

Math.max(...[1, 2, 3])

property values shorthand

function func() {
  return {1, 2};
}

let {x, y} = func();

classes

class Beep {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  toString() {
    return this.a + ' ' + this.b;
  }
}

function Beep(a, b) {
  this.a = a;
  this.b = b;
}
Beep.prototype.toString = function () {
  return this.a + ' ' + this.b;
}

super

class ColorPoint extends Point {
  constructor(x, y, color) {
    super(x, y);
    this.color = color;
  }
  toString() {
    return this.color + ' ' + super();
  }
}

static methods

class Point {
  static zero() {
    return new Point(0, 0);
  }
  constructor(x, y) {
    this.x = x; 
    this.y = y;
  }
}
let p = Point.zero();

generators

function* iterTree(tree) {
  if (Array.isArray(tree)) {
    // inner node
    for(let i=0; i < tree.length; i++) {
      traverseTree(tree[i], visitor); // (*) recursion
    }
  } else {
    // leaf
    visitor(tree);
  }
}

function* iterTree(tree) {
  if (Array.isArray(tree)) {
    // inner node
    for(let i=0; i < tree.length; i++) {
      yield* iterTree(tree[i]); // (*) recursion
    }
  } else {
    // leaf
    yield tree;
  }
}

template strings

allows for multi-line strings

templateHandler `hello ${first} ${last}!`

sets

let set1 = new Set();
set1.add('hello');
set1.has('hello'); // true

let set2 = new Set([3,2,1,3,2,3]);
set2.values(); // 1, 2, 3

Object.assign

Think _.extend()

class Point {
  constructor(x, y) {
    Object.assign(this, {x, y});
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment