Heyyy 👋🏻 ! My name is Christian, an Agile Software Developer, living in Trento (IT).
I am currently working at Wonderflow.
You can read more about me.

Chaining and indenting after the return statement

,
by

Share on Twitter

function lookupKey (object, objectNotation) {
  return objectNotation
        .split('.')
        .reduce((context, property) => context ? context[property] : null, object)
}

Code from husky-template.

Lately I have been following the Standard.JS style guide (after disliking ava & xo) and took style-guides in general more seriously.

Standard - JavaScript Style Guide

So the above code example shows a 100% “standard” JavaScript.

And I wanted to dig deeper on the two lines after the return statement.

Chaining and indentation

What I found to be a sane approach to indenting when chaining method calls is indenting the chain call by 6 spaces (or 3 tabs).

A small detail

Let’s do some maths:

assert.equal(7, 'return '.length)
assert.equal(7, '      .filter'.indexOf('.'))

return contains 6 letters and a space afterwards.

So we can indent by aligning the dot of the chain call to the space after the return to match it up horizontally.

return array
      .filter(...)
      .map(...)
      .reduce(...)

Ternary operator

function hasThis () {
  const or = true
  const that = false
  return this
        ? or
        : that
}

Code from has-this.

This is a personal choice, I follow it if I feel like it. Probably it feels more natural (read: less weird) if used with longer statements. But here again: does it really make my code more readable?


What do you think?