JavaScript ?:

Beginner
5 min read
Updated: Nov 2026
3 examples

Definition and Usage

The conditional (ternary) operator picks one of two expressions: condition ? valueIfTrue : valueIfFalse. It produces a value, so you can assign or return it.

JavaScript Syntax

JavaScript
const score = 80;
const grade = score >= 60 ? "pass" : "fail";
console.log(grade);
Try it Editor

How It Works

  1. Condition true. Chooses "pass".
  2. Assignable. Result stored in grade.

Examples

Example 1 — Keep it shallow

Nested ternaries get hard to read.

JavaScript
const n = 2;
console.log(n === 1 ? "one" : n === 2 ? "two" : "other");
Try it Editor

How It Works

  1. Prefer if/else for complex branches.

Example 2 — In returns

Handy in small functions.

JavaScript
const abs = (n) => (n < 0 ? -n : n);
console.log(abs(-3));
Try it Editor

How It Works

  1. Expression body returns the ternary result.

Example 3 — vs if...else

Use if for statements and side effects.

JavaScript
console.log("use if for multi-line branches");
Try it Editor

How It Works

  1. Ternary is for choosing values.

Frequently Asked Questions

No. It is an expression that yields a value.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful