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);
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.
The function name
property will be specified to match the existing de facto standards.
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...
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
Allow trailing parameters to have default values:
function inc(value, incBy = 1) {
return value + incBy;
}
assert(inc(0) === 1);
assert(inc(0, 5) === 5);
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);
Symetric to Rest Parameters
var list = [1, 2, 3, 4];
all(console.log, ...list);
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);
}