0
0
Javascriptprogramming~5 mins

Ternary operator in Javascript

Choose your learning style9 modes available
Introduction

The ternary operator helps you choose between two values quickly based on a condition. It makes your code shorter and easier to read.

When you want to set a value depending on a simple yes/no question.
When you want to print different messages based on a condition.
When you want to assign a variable quickly without writing a full if-else.
When you want to return one of two values from a function based on a check.
Syntax
Javascript
condition ? valueIfTrue : valueIfFalse;

The condition is a question that results in true or false.

If the condition is true, the operator returns valueIfTrue, otherwise it returns valueIfFalse.

Examples
Checks if age is 18 or more. If yes, canVote is 'Yes', else 'No'.
Javascript
let age = 18;
let canVote = age >= 18 ? 'Yes' : 'No';
Assigns 'Pass' if score is 60 or above, otherwise 'Fail'.
Javascript
let score = 75;
let grade = score >= 60 ? 'Pass' : 'Fail';
Prints 'Five is bigger' because 5 is greater than 3.
Javascript
console.log(5 > 3 ? 'Five is bigger' : 'Three is bigger');
Sample Program

This program checks if the temperature is above 25. If yes, it says 'Hot', otherwise 'Cold'. Then it prints the result.

Javascript
const temperature = 30;
const weather = temperature > 25 ? 'Hot' : 'Cold';
console.log(`The weather is ${weather}.`);
OutputSuccess
Important Notes

You can nest ternary operators but it can make code hard to read.

Use ternary operator for simple conditions to keep code clean.

Summary

The ternary operator is a shortcut for if-else statements.

It chooses between two values based on a condition.

It helps write shorter and clearer code for simple decisions.