Skip to content

Ternary Nesting is Ugly #5258

@gjcampbell

Description

@gjcampbell

Prettier 1.14.3
Playground link

Input:

const chainExample = someValue === 'a' ? 'a long non-nested ternary'
	: someValue === 'b' ? 'to demonstrate that'
	: someValue === 'c' ? 'a less ug style'
	: someValue === 'd' ? 'for line starts and indentation'
	: null;

const nestedExample = someValue === 'a' 
	? someValue === 'b' 
		? someValue === 'c' ? 'with a long nested ternary' 
			: 'not sure what to do here'
		: 'but indentation doesn\'t help enough' 
	: 'to connect results with the predicates'

Output:

const chainExample =
    someValue === "a"
        ? "a long non-nested ternary"
        : someValue === "b"
            ? "to demonstrate that"
            : someValue === "c"
                ? "indenting and newlines"
                : someValue === "d"
                    ? "are ug"
                    : null;

const nestedExample =
    someValue === "a"
        ? someValue === "b"
            ? someValue === "c"
                ? "with a long nested ternary"
                : "not sure what to do here"
            : "but indentation doesn't help enough"
        : "to connect results with the predicates";

Terminology
Given: condition ? exprT : exprF
Ternaries are chained when the exprF contains another ternary.
Ternaries are nested when the exprT contains another ternary.

Expected behavior:
When ternary statements are chained, do not over-indent, and use the : as the line start. When ternary statements are nested, do something else...

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:duplicateIssues that are a duplicate of a previous issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions