0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Ternary Operator in JavaScript: Syntax and Examples

The ternary operator in JavaScript is a shortcut for an if-else statement and uses the syntax condition ? valueIfTrue : valueIfFalse. It evaluates the condition and returns the first value if true, otherwise the second value.
📐

Syntax

The ternary operator has three parts:

  • condition: A test that results in true or false.
  • valueIfTrue: The value returned if the condition is true.
  • valueIfFalse: The value returned if the condition is false.

It is written as condition ? valueIfTrue : valueIfFalse.

javascript
let result = condition ? valueIfTrue : valueIfFalse;
💻

Example

This example checks if a number is even or odd using the ternary operator and prints the result.

javascript
const number = 7;
const result = (number % 2 === 0) ? 'Even' : 'Odd';
console.log(result);
Output
Odd
⚠️

Common Pitfalls

Common mistakes include:

  • Forgetting the colon : between the true and false values.
  • Using complex expressions that reduce readability.
  • Trying to use the ternary operator without assigning or returning its value.

Always keep ternary expressions simple and clear.

javascript
/* Wrong: Missing colon */
// let result = (5 > 3) ? 'Yes' 'No'; // SyntaxError

/* Right: Correct syntax with colon */
let result = (5 > 3) ? 'Yes' : 'No';
console.log(result);
Output
Yes
📊

Quick Reference

PartDescriptionExample
conditionExpression that evaluates to true or falsenumber > 10
?Separates condition and true value?
valueIfTrueReturned if condition is true'High'
:Separates true and false values:
valueIfFalseReturned if condition is false'Low'

Key Takeaways

Use the ternary operator as a concise alternative to simple if-else statements.
The syntax is: condition ? valueIfTrue : valueIfFalse.
Always include the colon to separate true and false values.
Keep ternary expressions simple to maintain code readability.
Ternary operator returns a value and can be assigned or returned directly.