Skip to main content

JavaScript Ternary Operator (Live Playground)

In this tutorial, we will explore the ternary operator, and learn how to use it in our code.

Ternary Operator (? :)

The ternary operator is a shorthand way of writing an if-else statement. It takes three operands: a condition, a value to return if the condition is true, and a value to return if the condition is false.


const a = 10;
const b = 20;
const result = a > b ? 'a is greater than b' : 'a is not greater than b';
console.log(result); // Output: 'a is not greater than b'
Live Playground, Try it Yourself


Understanding and using the ternary operator is essential for writing efficient and concise code in your JavaScript programs.