Please support this book: buy it (PDF, EPUB, MOBI) or donate

29. Coding style tips for ECMAScript 6

This chapter lists a few ideas related to ES6 coding style:

  • Prefer const. You can use it for all variables whose values never change.
  • Otherwise, use let – for variables whose values do change.
  • Avoid var.
    • An arrow function is the superior solution whenever a function fits into a single line:
  1. readFilePromisified(filename)
  2. .then(text => console.log(text))

For multi-line functions, traditional functions work well, too (with the caveat of this not being lexical):

  1. readFilePromisified(filename)
  2. .then(function (text) {
  3. const obj = JSON.parse(text);
  4. console.log(JSON.stringify(obj, null, 4));
  5. });

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.

  • Properties in object literals: As soon as an object literal spans multiple lines, I add a comma after the last entry. Such a trailing comma has been legal since ES5. It makes adding, removing and rearranging entries simpler. As a consequence, method definitions always end with },:
  1. const obj = {
  2. foo() {
  3. },
  4. bar() {
  5. },
  6. };
  • Modules: don’t mix default exports and named exports. Your module should either specialize on a single thing or export multiple, named, things.
    • Exception: Module with a default export that exposes some internals for testing (via named exports).
    • Details are explained in the chapter on modules.
  • Format generators as follows:
  1. // Generator function declaration
  2. function* genFunc() { ··· }
  3.  
  4. // Generator function expression
  5. const genFunc = function* () { ··· };
  6.  
  7. // Generator method definition in an object literal
  8. const obj = {
  9. * generatorMethod() {
  10. ···
  11. }
  12. };
  13.  
  14. // Generator method definition in a class definition
  15. class MyClass {
  16. * generatorMethod() {
  17. ···
  18. }
  19. }

Details are explained in the chapter on generators.

  1. // Mark optional parameters via the parameter default value `undefined`
  2. function foo(optional = undefined) { ··· }
  3.  
  4. // Mark required parameters via a function that throws an exception
  5. function foo(required = throwException()) { ··· }
  6.  
  7. // Enforcing a maximum arity (variant 1 of 2)
  8. function f(x, y, ...empty) { // max arity: 2
  9. if (empty.length > 0) {
  10. throw new Error();
  11. }
  12. }
  13. // Enforcing a maximum arity (variant 2 of 2)
  14. function f(x, y) { // max arity: 2
  15. if (arguments.length > 2) {
  16. throw new Error();
  17. }
  18. }
  • In the chapter on callable entities (traditional functions, arrow functions, classes, etc.) there is a section that gives recommendations (when to use which one etc.). Additionally, the ES5 coding style tips in “Speaking JavaScript” are still relevant for ES6.