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 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #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

#Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface #Jan 14 How to display a student’s individual transcript in Colleague? #Jan 11 How to install PuTTY on a MacOS? #Jan 8 How to Install Xcode Command Line Tools on MacOS?
You might also like these
Introduction to Angular modules Part 2: NgModules and componentsAngularHow to add Local State to a Class in React?ReactHow to install PuTTY on a MacOS?MiscellaneousHow to convert datetime to date format in JavaScript?JavaScriptHow to redirect or load a new document using JavaScript?JavaScriptHow to create HTML elements with ID and class using JavaScript?HTMLThe unique operator($) in Envision BasicEnvision BasicWhat are Null Sessions?MiscellaneousHow to obfuscate JavaScript code to hide it from View Source?JavaScriptCreate a simple bar chart and column chart using pure CSS gridCSSHow to create a for loop in SCSS (Sass)?SCSSFew more :nth-child examples in CSSCSS