Skip to content

Add braces when single-line ifs wrap #7888

@jakearchibald

Description

@jakearchibald

Prettier 1.18.2
Playground link

--parser babylon

Input:

function demo() {
  if (condition) throw Error('bad');
  if (earlyReturn) return true;
  if (anotherCondition) throw Error(`Nah this doesn't work for the following reasons…`);
}

Output:

function demo() {
  if (condition) throw Error("bad");
  if (earlyReturn) return true;
  if (anotherCondition)
    throw Error(`Nah this doesn't work for the following reasons…`);
}

Expected behavior:

I like single-line if statements for early exits and early throws, and I'm really happy that Pretty doesn't try and prevent that.

However, once the line length is reached, the statement goes onto the next line. Although single-line ifs are somewhat controversial, folks seem very much against the statement being on the following line. I've seen this go wrong in the wild, where folks don't realise the braces are missing, and add an extra statement that they expect to be part of the if. Prettier's formatting would correct the indenting of course, but maybe it's better to add the braces?

function demo() {
  if (condition) throw Error("bad");
  if (earlyReturn) return true;
  if (anotherCondition) {
    throw Error(`Nah this doesn't work for the following reasons…`);
  }
}

This has probably been discussed already, but I couldn't find an existing issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    lang:javascriptIssues affecting JSlocked-due-to-inactivityPlease open a new issue and fill out the template instead of commenting.type:questionQuestions and support requests. Please use Stack Overflow for them, not the issue tracker.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions