Skip to content

Latest commit

 

History

History
101 lines (67 loc) · 2.76 KB

File metadata and controls

101 lines (67 loc) · 2.76 KB
sidebar_position 2
title Ternary Operator
sidebar_label Ternary Operator
description Master the syntax and practical use cases of the Conditional (Ternary) Operator in JavaScript to write cleaner, more concise logic.
tags
javascript
ternary-operator
foundations
clean-code
logic

The Conditional (Ternary) Operator is the only JavaScript operator that takes three operands. It is frequently used as a one-line shortcut for the if...else statement, making your code significantly cleaner and more declarative.

:::info The word "Ternary" literally means "composed of three parts." :::

Basic Syntax

The syntax consists of a condition followed by a question mark (?), then an expression to execute if the condition is truthy, followed by a colon (:), and finally the expression to execute if the condition is falsy.

condition ? expressionIfTrue : expressionIfFalse;

For example:

const age = 20;
const canVote = age >= 18 ? 'Yes, you can vote!' : 'Not yet.';
console.log(canVote); // "Yes, you can vote!"

Understanding this syntax is crucial as it allows you to write more concise and readable code, especially when dealing with simple conditional logic.

Comparative Breakdown

const age = 20;
let canVote;

if (age >= 18) {
  canVote = "Yes, you can vote!";
} else {
  canVote = "Not yet.";
}

console.log(canVote); // "Yes, you can vote!"
const age = 20;

// Syntax: condition ? true : false
const canVote = age >= 18 ? "Yes, you can vote!" : "Not yet.";

console.log(canVote); // "Yes, you can vote!"

Why Use It?

The Ternary operator isn't just about saving space. In modern JavaScript (especially in frameworks like React), it allows you to:

  1. Assign values directly to a constant.
  2. Embed logic inside Template Literals.
  3. Return values from arrow functions without explicit return blocks.

Use Case: Dynamic Template Literals

const isPremium = true;

// Using ternary inside a string!
const welcomeMessage = `Welcome back, ${isPremium ? 'VIP Member' : 'Guest'}!`;

console.log(welcomeMessage); // "Welcome back, VIP Member!"

Interactive Playground

Test how the ternary operator handles state changes. In this demo, we check a "User Status" and change the theme dynamically.

:::tip Try changing the condition in the JS panel to check for a specific number or a boolean value to see how the UI updates instantly. :::