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

The Lending Club Analysis using Logistic Regression and Random Forest in RStudioMiscHow to include CSS and JavaScript files in your WordPress plugin?WordPressSolution to “NullInjectorError: No provider for module” in Angular 9AngularWhat happened to your Google Analytics Tracking ID, can’t find it?MiscHow to use GROUPING SETS to boost GROUP BY queries in Postgres?PostgresWhat’s the difference between variables in CSS and SCSS (Sass)?CSSRendering Elements in ReactReactArguments in @mixin rules in SCSS (Sass)SCSSSolution to pod install fails with json error on Mac OS X 10.15 (or Mac OS Catalina)MiscHow to change CSS with jQuery?CSSHow to draw an SVG path on scroll using JavaScript?JavaScriptHow to get previous days or next days in PHP?PHP