DEV Community

Cover image for Conditional Ternary Operators for Beginners
April Craig
April Craig

Posted on

Conditional Ternary Operators for Beginners

I’ve been hard at work exploring React. I’ve been following a React tutorial on FCC’s Youtube channel. While following along with the tutorial, the instructor used conditional ternary operators and that’s when I realized I have never really used them. I’ve seen the conditional ternary operator in use on several tutorials, but I’ve never really used them in my own code. So far I’ve learned the following.

According to MDN the Conditional Ternary Operator is a shortcut of an if statement and should be written using this syntax:

Condition? If true do this : If false do that

Here are some examples to clarify...

Example 1

function getAge(age){
return (age >=18? 'You are old enough': 'you are too young')
}
getAge(19)
//output: "You are old enough"

getAge(9)
//output: "you are too young"

The function getAge has a parameter of age. If the age is equal to or less than 18, the string 'You are old enough' is returned. If the age is under 18, the string 'you are too young' is returned.

Example 2

function isHungry(ateDinner){
 return (ateDinner ? 'Eat dinner': 'Drink some water')
}

isHungry(true)
//output: "Eat dinner"

isHungry(false)
//output: "Drink some water"

isHungry()
//output: "Drink some water"  null and undefined are considered falsy

The function isHungry has a parameter called ateDinner. When using ateDinner as a condition, if it is truthy ‘Eat Dinner’ will be returned. If ateDinner is falsy, ‘Drink some water’ will be returned instead. Take note of the last line. If the isHungry function is called without an argument it is falsy.

Example 3

let account = 1000;
let carPrice = (account >= 300) ? "You can buy the car" : "This car is too expensive";
console.log(carPrice)
//output: 'You can buy the car'

In this example, I am using the variable account as the condition for my conditional ternary operator.

Keep working...Keep striving...Keep coding!

Top comments (1)

Collapse
 
itachiuchiha profile image
Itachi Uchiha • Edited

When I was an intern at my current company I saw a ternary if written in PHP. It was like that;

$results = (
    $member 
       ? 
    $memberSelected 
      ? 
    $memberAdmin 
      ? 
    $memberSelected : $noMember : $memberTitle : $noMember
);

Really there was a code piece like above. I simplified the variable names to explain to you. Normally, variables are defined like that;

$m = '';
// updating variable $m while running app logic

$ms1 = $m;

$man += $ms1;

$m = ++$ms1;

I really didn't understand why the developer coded this code piece. I debugged this ternary if but I still didn't understand what this code does.

I completely removed this code piece and I got errors more than 100. I changed these 100 lines and I got nothing. I just saw a white screen. Nobody knew what that code does.