DEV Community

Discussion on: Keeping Your Code Simple

kepta profile image
Kushan Joshi • Edited on

I agree that the code you mentioned is terse, but in my humble opinion it is readable.

Everyone has their own definitions of readability. I think it is totally okay to have a terse lambda like the one you mentioned, as long as it is simply doing one thing and is reasonably small. In the example you posted it is simply comparing lengths of two strings and returning the longest. These type of short lambdas are pretty convenient and are pretty common in Javascript these days.
If you compare them side by side, the lambda version wins for me.

function longest(strs) {
  return strs.reduce((x, y) => {
    if (x.length > y.length)
      return x;
      return y;
  }, '');

const longest = strs => strs.reduce((s, t) => s.length >= t.length ? s : t); 

A code is clever when you yourself don't understand what it does a week later. To mitigate that you have to provide a verbose comment describing what the hell it does and pray to god that whoever changes the code also updates the comment, because in real life comments and code go out of sync pretty often.

Another important thing about the more terse option is that it improves readability when you start chaining operators. Let me give you a hypothetical example and you decide for yourself:

function longest(strs) {
  return strs
    .filter(s => {
      if (typeof s === 'string') {
        return true;
    .map(s => {
      if (/^[aeiou]/i.test(s)) return 'an ' + s;
      else return 'a ' + s;
    .reduce((x, y) => {
      if (x.length > y.length) return x;
      else return y;
    }, '');

const longest = strs =>
    .filter(s => typeof s === 'string')
    .map(s => (/^[aeiou]/i.test(s) ? 'an ' : 'a ') + s)
    .reduce((s, t) => (s.length >= t.length ? s : t));
  • Each individual piece is easy to reason with independently.
  • It has more inertia to code change, i.e. a fellow programmer cannot simply introduce a closure variable as easily as in the if else version. Hey we all have had that bug which was temporarily fixed by peppering code with global variables.
  • Less syntax noise.
  • I don't have to constantly fiddle around with closing {}.