Conditional operator in JavaScript (aka ternary operator)
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"


Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 3 How to embed YouTube or other video links in WordPress? Mar 3 How to change the Login Logo in WordPress? Mar 3 substring() Method in JavaScript Mar 3 Window setInterval() Method in JavaScript Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS

You might also like these

3 Types of Arrays in PHPPHPLIMIT and OFFSET in PostgresPostgresHow does AdSense calculate page loading time?JavaScriptHow to CREATE TABLE in SQL with and without using Another Table?SQL/MySQLHow to check if radio button is checked or not using JavaScript?JavaScriptPostgreSQL BETWEENPostgresHow to deploy Angular App on Dreamhost or Amazon S3 or firebase?AngularHow to create a simple tab interaction using CSS?CSSFull and Partial ROLLUP in Postgresql with ExamplesPostgresHow to link/add CSS file to HTML Document?CSSHow to insert Bootstrap 4 in Angular 9 app?AngularThe Differences Between HAVING Clause and WHERE Clause in SQLSQL/MySQL