Skip to content

JavaScript Tutorial Operators

JavaScript Ternary Operator

Lesson 27 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

The ternary operator picks one of two values based on a condition. It is the only JavaScript operator with three parts.

code
TEXT
condition ? valueIfTrue : valueIfFalse
script.js
JS
const age = 20;
const status = age >= 18 ? "adult" : "minor";
console.log(status); // → adult

It is a short form of this if/else:

script.js
JS
let status;
if (age >= 18) {
  status = "adult";
} else {
  status = "minor";
}

The big difference: the ternary is an expression, so it produces a value you can use directly. That makes it handy inside template literals and function calls.

script.js
JS
const items = 3;
console.log(`You have ${items} ${items === 1 ? "item" : "items"}`); // → You have 3 items

const isOnline = false;
console.log(isOnline ? "Online" : "Offline"); // → Offline

Updating the page

index.html
HTML
<button id="toggle">Toggle</button>
<p id="state">Off</p>
<script>
  let on = false;
  document.querySelector("#toggle").addEventListener("click", () => {
    on = !on;
    document.querySelector("#state").textContent = on ? "On" : "Off";
  });
</script>

Chaining (use with care)

You can chain ternaries, but readability drops fast.

script.js
JS
const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "D";

Two levels are fine. Beyond that, an if / else if chain (see else if) is easier to read.

When not to use it

  • When you need to do several things in each branch. Use if.
  • When you are not using the result. x > 5 ? doThis() : doThat(); works, but a plain if says what you mean.
lightbulb
A readability test
If you have to read a ternary twice to understand it, rewrite it as an if.