Skip to content

Latest commit

 

History

History
133 lines (89 loc) · 3.04 KB

es6.md

File metadata and controls

133 lines (89 loc) · 3.04 KB

ES6 Proposals

Function Improvements

Arrow Function Syntax

A shorthand syntax for functions:

let identity = x => x;
let square = x => x * x;
let fives = [];
nats.forEach(v => { if (v % 5 === 0) fives.push(v); });

this is bound lexically, rather than being dynamic

const obj = {
  method: function () {
    return () => this;
  }
};
assert(obj.method()() === obj);

more...

Function to String

Calling toString on a function must return the source code. If the function inheirted "use strict" from a parent context it must be added to the body of the source code.

more...

Function Name Property

The function name property will be specified to match the existing de facto standards.

more...

Scoping, Binding and Calling

Block Scoped Bindings

let is a new keyword that improves on var by providing block scoping and better use before set semantics. more...

const is like let, but doesn't allow you to modify a variable after creation. more...

block functions are let-scoped functions declared directly in block statements more...

Destructuring

Object and array desctructuring. Best explained with a few examples.

Swap two variables:

[a, b] = [b, a]

Multi-value returns:

function f() { return [1, 2] }
var [a, b] = f();

Object Destructuring:

var { op: a, lhs: { op: b }, rhs: c } = getASTNode()
// a, b and c now have the apropriate values

more... even more...

Optional Parameters

Allow trailing parameters to have default values:

function inc(value, incBy = 1) {
  return value + incBy;
}
assert(inc(0) === 1);
assert(inc(0, 5) === 5);

more...

Rest Parameters

Allows getting the remaining arguments of a function as an array:

function all(fn, ...args) {
  args.forEach(fn);
}
all(console.log, 1, 2, 3, 4);

more...

Spread Parameters

Symetric to Rest Parameters

var list = [1, 2, 3, 4];
all(console.log, ...list);

more...

Proper Tail Calls

Proper tail calls help optimise carefully designed recursive functions.

//not optimised
function factorial(n) {
  if (n === 0) return 1;
  else return n * factorial(n - 1);
}

//optimised
function factorial(n, acc = 1) {
  if (n === 0) return acc;
  else return factorial(n - 1, acc * n);
}

more...