This chapter lists a few ideas related to ES6 coding style:
var versus let versus const (details are explained in the chapter on variables):
const. You can use it for all variables whose values never change.let – for variables whose values do change.var. readFilePromisified(filename)
.then(text => console.log(text))
For multi-line functions, traditional functions work well, too (with the caveat of this not being lexical):
readFilePromisified(filename)
.then(function (text) {
const obj = JSON.parse(text);
console.log(JSON.stringify(obj, null, 4));
});
Single-line functions tend to be throw-away. If a function isn’t then a traditional function has the advantage that you can name it, which is useful for documentation and debugging.
},:
const obj = {
foo() {
},
bar() {
},
};
// Generator function declaration
function* genFunc() { ··· }
// Generator function expression
const genFunc = function* () { ··· };
// Generator method definition in an object literal
const obj = {
* generatorMethod() {
···
}
};
// Generator method definition in a class definition
class MyClass {
* generatorMethod() {
···
}
}
Details are explained in the chapter on generators.
// Mark optional parameters via the parameter default value `undefined`
function foo(optional = undefined) { ··· }
// Mark required parameters via a function that throws an exception
function foo(required = throwException()) { ··· }
// Enforcing a maximum arity (variant 1 of 2)
function f(x, y, ...empty) { // max arity: 2
if (empty.length > 0) {
throw new Error();
}
}
// Enforcing a maximum arity (variant 2 of 2)
function f(x, y) { // max arity: 2
if (arguments.length > 2) {
throw new Error();
}
}
Additionally, the ES5 coding style tips in “Speaking JavaScript” are still relevant for ES6.