Falytom logoFALYTOM
Games
ToolsUI ComponentsServicesProductsAbout
LoginSign Up
menu
  1. Home
  2. /Web Development
  3. /Javascript
  4. /Ternary Operator
Your Progress0%
0 of 61 completed

JavaScript Topics

Getting Started

  • What is JavaScript?
  • JavaScript vs Other Languages
  • Setting Up Your JavaScript Environment
  • Developer Console and Debugging Basics

JavaScript Fundamentals

  • Variables (var, let, const)
  • Data Types and Type Checking
  • Comments and Code Organization
  • String Methods and Template Literals
  • Type Conversion and Coercion
  • Operators (Arithmetic, Comparison, Logical)

Control Flow

  • If/Else Statements
  • Switch Statements
  • Ternary Operator
  • Truthy and Falsy Values
  • Logical Operators and Short-Circuiting

Loops and Iteration

  • For Loops
  • While and Do-While Loops
  • For...of and For...in Loops
  • Break and Continue Statements

Functions

  • Function Declarations and Expressions
  • Arrow Functions
  • Function Parameters and Arguments
  • Return Statements and Values
  • Scope and Closures
  • Higher-Order Functions and Callbacks

Arrays

  • Array Basics and Creation
  • Array Methods: Adding and Removing Elements
  • Array Iteration Methods (forEach, map, filter)
  • Array Methods: find, some, every, reduce
  • Sorting, Reversing, and Array Transformation

Objects

  • Object Basics and Properties
  • Object Methods and 'this' Keyword
  • Object Destructuring
  • Object.keys, values, entries
  • Spread Operator and Object Cloning

DOM Manipulation

  • Introduction to the DOM
  • Selecting Elements (querySelector, getElementById)
  • Modifying Elements (textContent, innerHTML, style)
  • Creating and Removing Elements
  • Event Listeners and Event Handling
  • Event Object and Event Delegation

Asynchronous JavaScript

  • Understanding Asynchronous Code
  • setTimeout and setInterval
  • Callbacks and Callback Hell
  • Promises and Promise Chaining
  • Async/Await

Error Handling

  • Try, Catch, Finally
  • Throwing Custom Errors

Modern JavaScript Features

  • ES6+ Overview
  • Modules (import/export)
  • Optional Chaining and Nullish Coalescing
  • Rest and Spread Operators

Working with Data

  • JSON (Parse and Stringify)
  • Fetch API and HTTP Requests
  • Working with Local Storage

Advanced Concepts

  • Classes and Object-Oriented Programming
  • Array and Object Advanced Patterns
  • Regular Expressions Basics

Best Practices & Real-World Application

  • JavaScript Best Practices
  • Debugging Techniques and Tools
  • Building a Complete Interactive Project

Ternary Operator

Shorthand for simple conditional expressions

The ternary operator is JavaScript's only operator that takes three operands. It's a concise way to write simple if/else statements in a single line, making your code cleaner and more readable when used appropriately. Think of it as a shortcut for quick decisions. Let's master this powerful tool!

What Is the Ternary Operator?

The ternary operator (also called the conditional operator) is a shorthand way to write an if/else statement. It evaluates a condition and returns one of two values based on whether the condition is true or false.

Why "ternary"?

"Ternary" means "composed of three parts." This operator has three parts: the condition, the value if true, and the value if false.

Basic Syntax

JAVASCRIPT
condition ? valueIfTrue : valueIfFalse

// Example
let age = 20;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status);  // "Adult"

How It Works

  1. JavaScript evaluates the condition before the ?
  2. If the condition is true, return the value after ?
  3. If the condition is false, return the value after :

Basic Ternary Examples

Simple Conditional Assignment

JAVASCRIPT
// Check if number is positive
let num = 10;
let sign = num >= 0 ? "positive" : "negative";
console.log(sign);  // "positive"

// Check if user is logged in
let isLoggedIn = true;
let message = isLoggedIn ? "Welcome back!" : "Please log in";
console.log(message);  // "Welcome back!"

// Even or odd
let number = 7;
let parity = number % 2 === 0 ? "even" : "odd";
console.log(parity);  // "odd"

// Temperature check
let temp = 30;
let weather = temp > 25 ? "hot" : "cold";
console.log(weather);  // "hot"

In Variable Declarations

JAVASCRIPT
// Discount based on membership
let isMember = true;
let discount = isMember ? 0.2 : 0.1;  // 20% or 10%
console.log(discount);  // 0.2

// Price with tax
let price = 100;
let includesTax = false;
let finalPrice = includesTax ? price : price * 1.08;
console.log(finalPrice);  // 108

// Default values
let username = "";
let displayName = username ? username : "Guest";
console.log(displayName);  // "Guest"

// Or use || operator for default values (more common)
let displayName2 = username || "Guest";
console.log(displayName2);  // "Guest"

Ternary vs If/Else

The ternary operator is a shorthand for simple if/else statements. Here's how they compare.

Same logic, different syntax

If/Else Statement

// Using if/else
let age = 20;
let status;

if (age >= 18) {
  status = "Adult";
} else {
  status = "Minor";
}

console.log(status);  // "Adult"

// More verbose, takes 7 lines
Output:
Not run yet...

Ternary Operator

// Using ternary
let age = 20;
let status = age >= 18 ? "Adult" : "Minor";

console.log(status);  // "Adult"

// Concise, just 1 line
// Same result, cleaner code
Output:
Not run yet...

Multiple Comparisons

Ternary shines for simple assignments

If/Else (Verbose)

// If/else for function return
function getDiscount(isMember) {
  if (isMember) {
    return 0.2;
  } else {
    return 0.1;
  }
}

// Setting class names
let isActive = true;
let className;
if (isActive) {
  className = "active";
} else {
  className = "inactive";
}
Output:
Not run yet...

Ternary (Concise)

// Ternary for function return
function getDiscount(isMember) {
  return isMember ? 0.2 : 0.1;
}

// Setting class names
let isActive = true;
let className = isActive ? "active" : "inactive";

// Much more concise!
Output:
Not run yet...

Ternary in Different Contexts

In Template Literals

JAVASCRIPT
let score = 85;
let message = `You ${score >= 60 ? "passed" : "failed"} the test.`;
console.log(message);  // "You passed the test."

let items = 3;
let cartMessage = `You have ${items} item${items !== 1 ? "s" : ""} in your cart.`;
console.log(cartMessage);  // "You have 3 items in your cart."

let temp = 30;
let tempMessage = `It's ${temp > 25 ? "hot" : "cold"} today (${temp}°C).`;
console.log(tempMessage);  // "It's hot today (30°C)."

In Function Arguments

JAVASCRIPT
function greet(name) {
  console.log(`Hello, ${name}!`);
}

let username = "";
greet(username ? username : "Guest");  // "Hello, Guest!"

// Or directly
greet(username || "Guest");  // Same result

// With calculations
function applyDiscount(price, isMember) {
  return price * (isMember ? 0.8 : 0.9);  // 20% or 10% off
}

console.log(applyDiscount(100, true));   // 80
console.log(applyDiscount(100, false));  // 90

In Return Statements

JAVASCRIPT
function isEven(num) {
  return num % 2 === 0 ? true : false;
}

// Actually, even simpler:
function isEvenBetter(num) {
  return num % 2 === 0;  // Already returns boolean!
}

// Good use of ternary in return
function getGrade(score) {
  return score >= 90 ? "A" :
         score >= 80 ? "B" :
         score >= 70 ? "C" :
         score >= 60 ? "D" : "F";
}

console.log(getGrade(85));  // "B"

// Ternary with objects
function getUserRole(isAdmin) {
  return isAdmin ? { role: "admin", access: "full" } : { role: "user", access: "limited" };
}

console.log(getUserRole(true));
// { role: "admin", access: "full" }

In JSX/React (Common Pattern)

JAVASCRIPT
// Ternary is very common in React for conditional rendering
// (This is React syntax, not plain JavaScript)

// Show login button or user menu
{isLoggedIn ? <UserMenu /> : <LoginButton />}

// Show loading or content
{isLoading ? <Spinner /> : <Content />}

// Conditional class names
<div className={isActive ? "active" : "inactive"}>

// Conditional styles
<button style={{ color: isPremium ? "gold" : "silver" }}>

// This is why ternary is so popular!

Nested Ternary Operators

You can nest ternary operators to handle multiple conditions. However, use this sparingly as it can become hard to read.

Basic Nesting

JAVASCRIPT
// Simple nested ternary
let score = 85;
let grade = score >= 90 ? "A" :
            score >= 80 ? "B" :
            score >= 70 ? "C" : "F";
console.log(grade);  // "B"

// How it works:
// 85 >= 90? No → check next
// 85 >= 80? Yes → return "B"

// Temperature categories
let temp = 30;
let category = temp > 30 ? "hot" :
               temp > 20 ? "warm" :
               temp > 10 ? "cool" : "cold";
console.log(category);  // "warm"

Formatting Nested Ternaries

JAVASCRIPT
// HARD TO READ: All on one line
let result = age >= 18 ? "adult" : age >= 13 ? "teen" : age >= 3 ? "child" : "toddler";

// BETTER: Format for readability
let result = age >= 18 ? "adult" :
             age >= 13 ? "teen" :
             age >= 3  ? "child" : "toddler";

// EVEN BETTER: Add parentheses for clarity
let result = (age >= 18) ? "adult" :
             (age >= 13) ? "teen" :
             (age >= 3)  ? "child" : "toddler";

// BEST: For complex logic, use if/else
let result;
if (age >= 18) {
  result = "adult";
} else if (age >= 13) {
  result = "teen";
} else if (age >= 3) {
  result = "child";
} else {
  result = "toddler";
}

When NOT to Use Nested Ternaries

JAVASCRIPT
// TOO COMPLEX: Don't do this!
let status = isLoggedIn ? 
             hasPermission ? 
             isVerified ? 
             "full-access" : "limited-access" : 
             "no-permission" : 
             "not-logged-in";

// MUCH BETTER: Use if/else
let status;
if (!isLoggedIn) {
  status = "not-logged-in";
} else if (!hasPermission) {
  status = "no-permission";
} else if (isVerified) {
  status = "full-access";
} else {
  status = "limited-access";
}

// Or use early returns in a function
function getStatus(isLoggedIn, hasPermission, isVerified) {
  if (!isLoggedIn) return "not-logged-in";
  if (!hasPermission) return "no-permission";
  if (isVerified) return "full-access";
  return "limited-access";
}

Best Practice: Limit ternary nesting to 2 levels maximum. If you need more complex logic, use if/else statements for better readability.

Ternary with Function Calls

JAVASCRIPT
// Call different functions based on condition
let isAdmin = true;
let action = isAdmin ? grantFullAccess() : grantLimitedAccess();

function grantFullAccess() {
  console.log("Full access granted");
  return { access: "full", permissions: ["read", "write", "delete"] };
}

function grantLimitedAccess() {
  console.log("Limited access granted");
  return { access: "limited", permissions: ["read"] };
}

// Execute function only if condition is true
let shouldLog = true;
shouldLog ? console.log("Logging...") : null;

// Better: Use short-circuit evaluation for this
shouldLog && console.log("Logging...");

// Ternary with method chaining
let text = "  hello  ";
let result = text ? text.trim().toUpperCase() : "";
console.log(result);  // "HELLO"

Common Ternary Patterns

Default Values

JAVASCRIPT
// Set default if value is falsy
let username = "";
let display = username ? username : "Guest";

// Or use || operator (more common)
let display2 = username || "Guest";

// Nullish coalescing operator (ES2020)
let display3 = username ?? "Guest";  // Only for null/undefined

// With ternary for explicit check
let count = 0;
let displayCount = count !== null && count !== undefined ? count : "N/A";
console.log(displayCount);  // 0 (not "N/A")

Boolean Toggle

JAVASCRIPT
// Toggle boolean value
let isVisible = true;
isVisible = isVisible ? false : true;

// Better: Use NOT operator
isVisible = !isVisible;

// Toggle between two values
let theme = "light";
theme = theme === "light" ? "dark" : "light";
console.log(theme);  // "dark"

// Toggle again
theme = theme === "light" ? "dark" : "light";
console.log(theme);  // "light"

Pluralization

JAVASCRIPT
// Add 's' for plural
let count = 5;
let message = `You have ${count} item${count !== 1 ? "s" : ""}.`;
console.log(message);  // "You have 5 items."

// Works for 1
count = 1;
message = `You have ${count} item${count !== 1 ? "s" : ""}.`;
console.log(message);  // "You have 1 item."

// More complex pluralization
function getItemsText(count) {
  return count === 0 ? "no items" :
         count === 1 ? "1 item" :
         `${count} items`;
}

console.log(getItemsText(0));   // "no items"
console.log(getItemsText(1));   // "1 item"
console.log(getItemsText(10));  // "10 items"

Validation Feedback

JAVASCRIPT
// Form validation
let password = "abc123";
let isValid = password.length >= 8;
let feedback = isValid ? "✓ Valid password" : "✗ Password too short";
console.log(feedback);  // "✗ Password too short"

// Color coding
let score = 75;
let color = score >= 80 ? "green" :
            score >= 60 ? "yellow" : "red";
console.log(color);  // "yellow"

// Icon based on status
let status = "success";
let icon = status === "success" ? "✓" :
           status === "error" ? "✗" :
           status === "warning" ? "⚠" : "ℹ";
console.log(icon);  // "✓"

When to Use Ternary vs If/Else

Use Ternary When:

  • Assigning one of two values to a variable
  • Returning one of two values from a function
  • The condition and values are simple and clear
  • It fits comfortably on one line (or 2-3 formatted lines)
  • You want concise, readable code
  • Both outcomes are single expressions

Use If/Else When:

  • Executing multiple statements in each branch
  • The condition is complex with multiple checks
  • You need more than 2-3 nested conditions
  • The logic needs comments to explain
  • Either branch has side effects or complex operations
  • Readability would suffer with ternary
JAVASCRIPT
// GOOD use of ternary
let status = isLoggedIn ? "active" : "inactive";
let price = isMember ? 9.99 : 19.99;
let message = hasError ? "Error occurred" : "Success";

// BAD use of ternary (use if/else instead)
let result = condition ? 
             (doSomething(), calculateValue(), updateDatabase(), returnValue()) :
             (logError(), sendAlert(), showMessage(), defaultValue());

// GOOD: Multiple statements need if/else
if (condition) {
  doSomething();
  calculateValue();
  updateDatabase();
  result = returnValue();
} else {
  logError();
  sendAlert();
  showMessage();
  result = defaultValue();
}

Practical Examples

Example 1: User Greeting

JAVASCRIPT
function greetUser(user) {
  // Check if user exists and has name
  let name = user && user.name ? user.name : "Guest";
  
  // Get time of day
  let hour = new Date().getHours();
  let timeGreeting = hour < 12 ? "Good morning" :
                     hour < 18 ? "Good afternoon" : "Good evening";
  
  // Combine
  return `${timeGreeting}, ${name}!`;
}

console.log(greetUser({ name: "John" }));
// "Good morning, John!" (if morning)

console.log(greetUser(null));
// "Good morning, Guest!"

Example 2: Button States

JAVASCRIPT
function getButtonConfig(isLoading, isDisabled, hasError) {
  return {
    text: isLoading ? "Loading..." :
          hasError ? "Try Again" : "Submit",
    
    className: isDisabled ? "btn-disabled" :
               hasError ? "btn-error" : "btn-primary",
    
    icon: isLoading ? "⌛" :
          hasError ? "⚠️" : "✓",
    
    enabled: !isLoading && !isDisabled
  };
}

console.log(getButtonConfig(true, false, false));
// { text: "Loading...", className: "btn-disabled", icon: "⌛", enabled: false }

console.log(getButtonConfig(false, false, true));
// { text: "Try Again", className: "btn-error", icon: "⚠️", enabled: true }

Example 3: Data Formatting

JAVASCRIPT
function formatPrice(price, includeCurrency = true) {
  let formatted = price.toFixed(2);
  return includeCurrency ? `$${formatted}` : formatted;
}

console.log(formatPrice(19.99));        // "$19.99"
console.log(formatPrice(19.99, false)); // "19.99"

function formatPhoneNumber(phone, includeCountryCode = false) {
  // Assume phone is 10 digits
  let formatted = `(${phone.slice(0,3)}) ${phone.slice(3,6)}-${phone.slice(6)}`;
  return includeCountryCode ? `+1 ${formatted}` : formatted;
}

console.log(formatPhoneNumber("1234567890"));
// "(123) 456-7890"

console.log(formatPhoneNumber("1234567890", true));
// "+1 (123) 456-7890"

Ternary Operator Practice

Experiment with ternary expressions

Output:
Click "Run" to execute your code...
💡 Tip: Use console.log() to see your output in the console above.

Key Takeaways

  • Ternary syntax: condition ? valueIfTrue : valueIfFalse
  • It's a shorthand for simple if/else statements
  • Perfect for conditional assignments and returns
  • Works great in template literals and JSX
  • Can be nested but limit to 2-3 levels maximum
  • Use parentheses for clarity in complex conditions
  • Format nested ternaries vertically for readability
  • Don't use for multiple statements or complex logic
  • If it's hard to read, use if/else instead
  • Common patterns: defaults, pluralization, toggles, validation

What's Next?

You now know how to use the ternary operator to write concise conditional expressions! It's a powerful tool when used appropriately— perfect for simple decisions and inline conditions.

In the next lesson, we'll dive deep into Truthy and Falsy Values—understanding which values JavaScript treats as true or false in boolean contexts. This is crucial for writing effective conditions and avoiding common bugs!

💪 Practice Challenge:

Before moving on, try creating:

  1. A function that returns different messages based on score ranges using nested ternaries
  2. A greeting function that uses ternary to handle morning/afternoon/ evening
  3. A discount calculator that uses ternary to apply different rates
  4. A status indicator that returns different emojis based on connection state
  5. A pluralization helper that handles singular/plural forms with ternary

Test Your Understanding

Question 1 / 4

What will this ternary operator return?

let age = 20;
let status = age >= 18 ? 'Adult' : 'Minor';
Score: 0 / 0

Learning JavaScript's concise conditional operator! ❓

Previous
Switch Statements
Next
Truthy and Falsy Values

Continue Learning JavaScript

Join 2,000+ developers mastering JavaScript fundamentals. New lessons weekly - 100% FREE.

You might also like

UI Components

Ready-made components for your projects

Developer Tools

Boost productivity with handy generators

HTML Game

Learn HTML concepts through interactive gameplay

Join Our Web Development Training Program

Master frontend & backend development with hands-on projects.

JavaScript Tutorials

0 of 61 completed

Your Progress0%

Topics

Getting Started

  • What is JavaScript?
  • JavaScript vs Other Languages
  • Setting Up Your JavaScript Environment
  • Developer Console and Debugging Basics

JavaScript Fundamentals

  • Variables (var, let, const)
  • Data Types and Type Checking
  • Comments and Code Organization
  • String Methods and Template Literals
  • Type Conversion and Coercion
  • Operators (Arithmetic, Comparison, Logical)

Control Flow

  • If/Else Statements
  • Switch Statements
  • Ternary Operator
  • Truthy and Falsy Values
  • Logical Operators and Short-Circuiting

Loops and Iteration

  • For Loops
  • While and Do-While Loops
  • For...of and For...in Loops
  • Break and Continue Statements

Functions

  • Function Declarations and Expressions
  • Arrow Functions
  • Function Parameters and Arguments
  • Return Statements and Values
  • Scope and Closures
  • Higher-Order Functions and Callbacks

Arrays

  • Array Basics and Creation
  • Array Methods: Adding and Removing Elements
  • Array Iteration Methods (forEach, map, filter)
  • Array Methods: find, some, every, reduce
  • Sorting, Reversing, and Array Transformation

Objects

  • Object Basics and Properties
  • Object Methods and 'this' Keyword
  • Object Destructuring
  • Object.keys, values, entries
  • Spread Operator and Object Cloning

DOM Manipulation

  • Introduction to the DOM
  • Selecting Elements (querySelector, getElementById)
  • Modifying Elements (textContent, innerHTML, style)
  • Creating and Removing Elements
  • Event Listeners and Event Handling
  • Event Object and Event Delegation

Asynchronous JavaScript

  • Understanding Asynchronous Code
  • setTimeout and setInterval
  • Callbacks and Callback Hell
  • Promises and Promise Chaining
  • Async/Await

Error Handling

  • Try, Catch, Finally
  • Throwing Custom Errors

Modern JavaScript Features

  • ES6+ Overview
  • Modules (import/export)
  • Optional Chaining and Nullish Coalescing
  • Rest and Spread Operators

Working with Data

  • JSON (Parse and Stringify)
  • Fetch API and HTTP Requests
  • Working with Local Storage

Advanced Concepts

  • Classes and Object-Oriented Programming
  • Array and Object Advanced Patterns
  • Regular Expressions Basics

Best Practices & Real-World Application

  • JavaScript Best Practices
  • Debugging Techniques and Tools
  • Building a Complete Interactive Project
Falytom logoFALYTOM

Learn technologies like HTML, CSS, JavaScript, React, NodeJS and more through interactive games, tutorials, components and free tools. Transform your businesses with AI chatbots, SEO-optimized websites, and professional development services.

© 2025 Tomilola Group
  • Facebook logo
  • Twitter logo
  • Instagram logo
  • LinkedIn logo
  • GitHub logo
  • YouTube logo