Example 1 — Keep it shallow
Nested ternaries get hard to read.
JavaScript
const n = 2;
console.log(n === 1 ? "one" : n === 2 ? "two" : "other"); How It Works
- Prefer if/else for complex branches.
The conditional (ternary) operator picks one of two expressions: condition ? valueIfTrue : valueIfFalse. It produces a value, so you can assign or return it.
const score = 80;
const grade = score >= 60 ? "pass" : "fail";
console.log(grade); Nested ternaries get hard to read.
const n = 2;
console.log(n === 1 ? "one" : n === 2 ? "two" : "other"); Handy in small functions.
const abs = (n) => (n < 0 ? -n : n);
console.log(abs(-3)); Use if for statements and side effects.
console.log("use if for multi-line branches"); CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful