How to use the ternary to if/else converter
- Paste your code into the JavaScript box, one statement per line.
- Copy the if/else version. Lines without a ternary are kept as they were.
- Check Statements converted to see how many lines were expanded.
What it does and when to use it
A short ternary is neat. A nested one, such as a grade calculation with three outcomes, is hard to read, hard to step through in a debugger, and hard to extend with an extra line of logging. Use this tool when you review or refactor that kind of code, when you add a breakpoint to one branch, or when you teach how ? : maps to if.
The reverse direction and other refactors have their own tools: var to let / const modernises declarations, and the JavaScript formatter lays out the result. To confirm the converted code still parses, use the JavaScript validator.
How it works
Each line is checked against four statement shapes:
| Shape | Example | Becomes |
|---|---|---|
| Declaration | const x = c ? a : b; |
let x; plus x = a / x = b |
| Assignment | total += c ? a : b; |
the same += in each branch |
| Return | return c ? a : b; |
return a; / return b; |
| Expression | c ? f() : g(); |
f(); / g(); |
The tool finds the first ? outside any brackets and the : that matches it, skipping ?. and ??. If the “else” part is itself a ternary, it becomes an else if branch, up to 50 levels. Brackets that wrap a whole condition are removed, and the original indentation is kept.
Worked examples
A declaration. const label = count === 1 ? 'item' : 'items'; becomes:
let label;
if (count === 1) {
label = 'item';
} else {
label = 'items';
}
A nested return. return score >= 90 ? 'A' : score >= 75 ? 'B' : 'C'; becomes an if, an else if (score >= 75) and a final else returning 'C'.
A compound assignment. total += isMember ? price * 0.9 : price; becomes:
if (isMember) {
total += price * 0.9;
} else {
total += price;
}
Not recognised. A ternary split over three lines returns “No ternary statements were recognised. Put each statement on its own line, e.g. const x = cond ? a : b;”.
Limits and tips
- One statement at a time. A statement over several lines is skipped. Several statements on one line are split at their semicolons and converted one by one.
- Side effects run the same way. Only the chosen branch runs in both forms, so function calls in the branches behave as before.
- Destructuring declarations such as
const { a } = c ? x : y;are left unchanged; rewrite those by hand. - Run the validator afterwards, since the converter matches text patterns rather than parsing the code.
Frequently asked questions
Why does const become let?
Will optional chaining or ?? confuse it?
My ternary is spread over several lines. What can I do?
Can it convert a ternary inside a function call or JSX?
Is the if/else version slower?
How do we know nothing is uploaded? Test it yourself on the privacy proof page.