Yogesh Chauhan's Blog

Conditional operator in JavaScript (aka ternary operator)

in JavaScript on February 15, 2021

Conditional operator is nothing but the shorthand for the long if else statement.

We can save lots of time by skipping the whole if else statements and just writing down the one line conditional operator.

The conditional operator takes three operands:

  1. a condition followed by a question mark (?)
  2. an expression to execute if the condition is true, followed by a colon (:)
  3. the expression to execute if the condition is false.

We can make a quick syntax using the list above:

condition ? expression to execute if the condition is TRUE : expression to execute if the condition is FALSE

If condition is null, 0, NaN, undefined or the empty string (“”), then the result of the conditional expression will be the FALSE.


One Condition

var x = 0;
var y = (x >= 0) ? "Positive" : "Negative";
// "Positive"

Multiple Conditions (Conditional chains)

Conditional chain is nothing but if… else… if… else… chain.

We can write the above example with multiple conditions.

var x = -1;
var y = (x > 0) ? "Positive" 
      : (x == 0) ? "Neutral"
      : "Negative";
// "Negative"

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
What is the difference between let and var in Swift?SwiftSocial Media Colors: LESS VariablesMiscellaneousContent types in DrupalDrupalIs there a way to do a FULL OUTER JOIN in MySQL?SQL/MySQLHow Do You Make a Private VPN?MiscellaneousHow to create rotating texts using JavaScript and CSS?CSSLIKE and ILIKE Operators in PostgresPostgresKilling A Project Part 4: What Would Be Your Top 3 Priorities For Planning The Cancellation?MiscellaneousSanitize inputs using built-in WordPress functionsWordPressCREATE TABLE Examples in PostgreSQLPostgresCheck whether a variable exists and not empty in PHPPHP@use rule in SCSS (Sass)SCSS