Skip to content

Implicit return – one line vs. one expression #438

Description

@tomek-he-him

Hello again. I have a subjective suggestion.

Point 8.2 says: “If the function body fits on one line and there is only a single argument, feel free to omit the braces and parentheses, and use the implicit return. Otherwise, add the parentheses, braces, and use a return statement.”. To be honest, this is the only rule I don’t keep to in my projects.

Simple function expressions – a set of arguments mapping to a single expression – are at the very heart of functional languages like JavaScript.

Consider this example:

[/* … */]
  .map(number => `A string containing the ${number}.`)
  /* … */

// As time goes by, the code evolves…
[/* … */]
  .map((number) => (
    `The string containing the ${number} now became much longer. A common ` +
    'thing to do when a line of code outgrows its 80 character limit is to ' +
    'break it over multiple lines.'
  ))
  /* … */

// That looks more natural to the language than:
[/* … */]
  .map((number) => {
    return (
      `The string containing the ${number} now became much longer. A common ` +
      'thing to do when a line of code outgrows its 80 character limit is to ' +
      'break it over multiple lines.'
    );
  ))
  /* … */

I suggest changing that guideline to the following:

If the function body fits on one line and there is only a single argument consists of a single expression, feel free to omit the braces and parentheses, and use the implicit return. When your expression spans over multiple lines, wrap it in parentheses for better readability. Otherwise, add the parentheses, braces and use a return statement.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions