Use Ternary Operators - Daily JavaScript Tips #2

Use Ternary Operators - Daily JavaScript Tips #2

Dhairya Shah's photo
Dhairya Shah
·Jan 9, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

TL;DR The ternary operator is a shortcut for if/else

It contains three operands

  • A condition
  • A question mark ?
  • A colon :

if/else

let fruit;
if(fruit === "Apple"){
    return "It is a fruit";
}else{
    return "It is not a fruit";
}

Ternary operators

let fruit;
let ternary = (fruit === "Apple") ? "It is a fruit" : "It is not a fruit";

See how it got executed in one line


Thank you for reading

 
Share this