DEV Community

Discussion on: Keeping Your Code Simple

Collapse
 
tbodt profile image
tbodt

I would probably end up using a for loop for this, but here's the most readable version using reduce I could think of:

function longestString(strs) {
  return strs.reduce((x, y) => {
    if (x.length > y.length)
      return x;
    else
      return y;
  }, '');
}
Collapse
 
fc250152 profile image
Nando

imho this solution is cleaner only for guys not used to ternary expressions, otherwise the first proposed solution is the better one; I don't think that the "if" solution does add any bit of clarity.

Collapse
 
tiffany profile image
tiff

Makes sense. I was trying to piece together CL's function from bits and pieces of a Twitter DM when I wrote this article. It's definitely not optimal. I should have asked him to clarify however he's a low level programmer not as familiar with Javascript.