Skip to content

Recommended ?: refactoring is worse #1677

@erights

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.

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