YogeshChauhan . com

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.

Examples

One Condition


var x = 0;
var y = (x >= 0) ? "Positive" : "Negative";
console.log(y); 
// "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";
console.log(y); 
// "Negative"

amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

Check if any column has NULL values in PostgresPostgresMicroservices vs Monolithic ArchitectureMiscWhat are Modules and Components in Angular?AngularA Step by Step Guide to Make RSS in XML For Any Website or Blog For FreeMiscHow to add Google Map in WordPress using ACF?WordPressSequence generator (range) using JavaScript Array.from()JavaScriptHAVING Clause in Postgres with Examples in All Aggregate FunctionsPostgresHow to get current timestamp in Swift 4 and 5?SwiftCREATE TABLE Examples in PostgreSQLPostgresLearn how to give a temporary name to a column or to a table using SQL AliasesSQL/MySQLHow to uninstall Cocoapods from the Mac OS?MiscJavaScript Input Validation Theme Park Example using throw StatementJavaScript