Skip to main content

Command Palette

Search for a command to run...

Ternary Operators In JavaScript

Updated
2 min read
Ternary Operators In JavaScript
S
Relentlessly curious and fiercely high‑agency, I'm a senior software engineer who thrives on taking products from zero to production‑ready in record time. Having worked across startups and fast-paced organizations, I've built a reputation as a cracked engineer who solves hard problems fast and owns the entire product stack end-to-end. My knack for rapid problem‑solving and end‑to‑end ownership turns complex ideas into polished, scalable products that ship fast and scale even faster. phewww... I love a cup of coffee ☕ while writing code. So let's connect and have a meet over something you wanna discuss. I'll be more than happy to have it. Book a call with me: https://cal.com/xshivank

Introduction

In Javascript, ternary operators are a shorthand way of writing conditional statements. Ternary operators involve three operands:

  • A condition

  • An expression that is to be executed if the condition is true

  • An expression that is to be executed if the condition is false

The syntax of ternary operators is given below:

condition ? expression1 : expression2

In the above code, a condition is any expression that can be evaluated either as true or false. If the condition is true, then the expression1 is executed else the expression2 is executed.

Some Examples

Example 1: Basics

var isTrue = true;
var output = isTrue ? 'Yes' : 'No';
console.log(output); //will print the output as 'Yes'

In the given example, we declare a variable isTrue with a default value of true. Then we use a ternary operator to assign the string 'Yes' to the output variable if isTrue is true. Since isTrue is true, the final result in the console will be 'Yes'.

Example 2: Nested Ternary Operators

var num = 0;
var result = num > 0 ? 'Positive' : num < 0 ? 'Negative' : 'Zero';
console.log(result); //will print the output as 'Zero'

In the above example, we defined a variable num with an initial value of 0. Here, we used a nested ternary operator in case if the variable num is greater than 0 then the string 'Positive' will be displayed, the string 'Negative' would be displayed if the variable num is less than 0 and 'Zero' would be displayed if the variable num is equal to 0.

Since the num variable is equal to 0 then the output in the console will be 'Zero'.

I hope that you must have found this article quite helpful. If yes, then do give a read to some of my other articles!

Who knows you might become a great programmer 🤔!

More from this blog

Shivank Kapur

57 posts

learning distributed systems 🦀 / dev-rel eng @routerprotocol / member @superteam / previously @thedogecapital @pushprotocol