Edit Template
  • Home
  • /
  • Ternary Operator
Edit Template
  • Home
  • /
  • Ternary Operator

Ternary Operator

In JavaScript, the ternary operator is a neat way to write quick, compact decisions—almost like a mini if-else that fits on one line.

It works like this:

				
					condition ? resultIfTrue : resultIfFalse


				
			

Instead of writing multiple lines of if-else, you can use this format to keep your code clean and simple.

Example

Let’s say you’re building a temperature-check feature on your weather app. You want to show a message based on whether it’s hot or cold.

				
					let temperature = 35;
let message = (temperature > 30) ? "It's hot outside!" : "Enjoy the cool weather!";
console.log(message); // Output: It's hot outside!

				
			

Here, JavaScript checks if the temperature is above 30. If true, it returns the message "It's hot outside!"; otherwise, it says "Enjoy the cool weather!".

When to Use It

  • Assigning values based on a condition

  • Returning different outputs in a single line

  • Simple decision-making logic

Scroll to Top