Welcome to the ExamAdda's Text Editor

Start creating amazing content with our feature-rich editor. You can format text, add images, create tables, and much more!

Use the toolbar above to format your content and create engaging articles.

As you write more JavaScript, you’ll often see code that looks shorter and cleaner than regular if-else. That’s usually because of the ternary operator.

The ternary operator is a compact way to write simple conditions in JavaScript.

What is the Ternary Operator in JavaScript?

The ternary operator is a short form of if-else

.It allows you to make decisions in just one line of code.

In simple terms:

Condition ? Do this if true : Do this if false

Basic Syntax

Simple Example

If age is 18 or more, the result will be "Adult".

 Otherwise, it will be "Minor".

When Should You Use the Ternary Operator?

Use it when:

  • The condition is simple

  • You want cleaner code

  • You are assigning a value based on a condition

Avoid using it for complex logic, as it can reduce readability.

The ternary operator is a powerful tool for writing clean and modern JavaScript. For beginners, it may look confusing at first, but with practice, it becomes one of the most useful shortcuts in your coding toolkit.

Mastering this will help you write more professional and readable code.