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.

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"


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #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
You might also like these
What’s a Closure in JavaScript?JavaScriptHow to auto-resize textarea based on text input using JavaScript or jQuery?JavaScriptColleague UI Basics: Accessing the user interfaceColleagueDoes :is() pseudo selector hint at CSS preprocessing in the future?CSS4 ways to create Date Objects in JavaScriptJavaScriptrandom function in SCSS (Sass)SCSSWhat is a Strict Requirement in PHP 7 Function Declarations?PHPHow to scroll contents of HTML body horizontally and vertically using JavaScript?JavaScriptContent types in DrupalDrupalHAVING Clause in Postgres with Examples in All Aggregate FunctionsPostgresHow to display random posts in WordPress?WordPressRecursive WITH Queries in Postgres (Common Table Expressions)Postgres