Skip to content

Recommended ?: refactoring is worse #1677

Description

@erights

https://github.com/airbnb/javascript#comparison--nested-ternaries

The recommended refactoring of

const foo = maybe1 > maybe2
  ? "bar"
  : value1 > value2 ? "baz" : null;

into

const maybeNull = value1 > value2 ? 'baz' : null;
const foo = maybe1 > maybe2 ? 'bar' : maybeNull;

is not equivalent. In the latter, the value1 > value2 comparison is always evaluated, and one of 'baz' or null is also always evaluated. In this case, it is probably fine, but in general it has two problems:

  • These extra evaluations may be expensive
  • These extra evaluations may have side effects or throw when maybe1 > maybe2.

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