DEV Community

Cover image for Use Ternary Operators - Daily JavaScript Tips #2
Dhairya Shah
Dhairya Shah

Posted on • Originally published at codewithsnowbit.hashnode.dev

Use Ternary Operators - Daily JavaScript Tips #2

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";
}
Enter fullscreen mode Exit fullscreen mode

Ternary operators

let fruit;
let ternary = (fruit === "Apple") ? "It is a fruit" : "It is not a fruit";
Enter fullscreen mode Exit fullscreen mode

See how it got executed in one line


Thank you for reading

Top comments (4)

Collapse
 
pengeszikra profile image
Peter Vivo

Better combination with arrow function than if/else.

const appleCheck = (fruit) => ternary = (fruit === "Apple") 
  ? "It is a fruit" 
  : "It is not a fruit"
;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dawsoncodes profile image
Dawson Codes

Even better:

const appleCheck = (fruit) => fruit === "Apple" ? "It is a fruit" : "It is not a fruit"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pengeszikra profile image
Peter Vivo

my previous version contain much more readable ternary formatting.

Collapse
 
mrhabibi profile image
Mr.Habibi

finally, Apple is a fruit...