DEV Community

David Okpare
David Okpare

Posted on

Ternary Operators In JavaScript

Are you tired of repeating yourself while coding? Do you still use the traditional ‘if…else’ blocks? What if I told you, you could write 15 lines of code in 4 lines? Call 1–800-TERNARY-OPERATORS now.

In computer programming, ?: is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages.

Ternary Operators are the shorthand version of if…else statements. It is the only conditional operator in JavaScript that takes three operands.

The basic syntax for ternary operators is condition ? expression1 : expression2

  • where the condition is the value to be tested/evaluated,

  • expression1 can be value(s) of any type to be executed if the condition is true

  • expression2 can be value(s) of any type to be executed if expression1 is false i.e fallback value commonly know as ‘else’

  • “ ? ” means “IF”, and “ : “ means “else”

Let’s look at an example

If we were to determine if one is allowed to drive by their ages, using the if…else statements — it looks something like this

var age = 18;

if (age >= 16) {
   alert("You're allowed to drive!");
}

else {
   alert("You should be 16 to drive!");
}

// "You're allowed to drive!"

Enter fullscreen mode Exit fullscreen mode

Using ternary operators, the same code will look like this

var age = 18;

alert (age >= 16) ? "You're allowed to drive!" : "You should be 16 to drive!"

// You're allowed to drive!

Enter fullscreen mode Exit fullscreen mode

Voila! This block of code will translate to IF variable ‘age’ is greater or equal to 16, the browser should alert ‘You’re allowed to drive!’, ELSE ‘You should be 16 to drive!’ should be alerted!

Another reason to adopt ternary, is it’s flexibility and miniature size which could fit anywhere in your code. For example, if you want to attach the the result of your string directly to a string, you can easily do that without having to declare your condition separately.

var isMember = true;
'The fee is ' + (isMember ? '$2.00' : '$10.00'); // The fee is $2.00
Enter fullscreen mode Exit fullscreen mode

IF isMember is true , ‘The fee is $2.00’, ELSE ‘The fee is $10.00’.

Guess what?! You can also assign the results of the ternary operations to variables. Let’s use the same driving example we used earlier.

var age = 18;
var canDrive = (age >= 16) ? "You're allowed to drive!" : "You should be 16 to drive!";
console.log(canDrive); // "You're allowed to drive!"
Enter fullscreen mode Exit fullscreen mode

In this example, we saved the result in a variable and later displayed it in the console.

There’s just as much possible in ternary operators as in the traditional if…else block. Multiple ternary operators can be chained together to form what we call ‘IF…ELSE IF…ELSE” block.

var year = prompt('Which year was the 2018 World Cup?', '');
alert(year < 2018) ? 'Too early' : (year > 2018) ? 'Too late' : 'Exactly!'; 

// Exactly!
Enter fullscreen mode Exit fullscreen mode

The block of code above will translate if the year is less than 2018, the browser should alert ‘Too early’, or else, if the year is greater than 2018, ‘Too late’ will be displayed, else if it’s not greater or lesser than i.e equal to, then ‘Exactly’ will be displayed.

You can also have nested if statements:

var statement1 = true;
var statement2 = true;

var check = statement1 ? (statement2 ? "True, Yes!" : "True, False!") : 'False';

console.log(check); // True, Yes!
Enter fullscreen mode Exit fullscreen mode

Our eyes scans codes vertically, which indentation and spaces play great parts in helping us read the codes easily. They are not excluded in ternary, and free spaces don’t affect your code.

var stop = false, age = 23;

age > 18 ? (
    alert('OK, you can go.')
) : (
    alert('Sorry, you are much too young!')
);
Enter fullscreen mode Exit fullscreen mode

The code above will work just as well as any ternary evaluation or any if…else operation.

It is also possible to have multiple operations per case, and separate them with a comma.

var age = 16;

var auth = age > 18 ? (
    alert('OK, you can go.'), 
    // alert returns "undefined", but it will be ignored because
    // isn't the last comma-separated value of the parenthesis
    'APPROVED' // the value to be assigned if age > 18
) : (
    alert('You are much too young!'),
    alert('Sorry :-('),
    // etc. etc.
    'DISAPPROVE' // the value to be assigned if !(age > 18)
);

location.assign(auth); // "DISAPPROVE"
Enter fullscreen mode Exit fullscreen mode

Last but not the least, ternary operations can be used to return values in functions. For example, if we were to write a function to return a value to determine if Chris Pratt is a member of the Marvel Universe or not;

var marvel = true;

function chrisPratt(marvel) {
  if (marvel === true){
return "I am Star-Lord!";
}
else {
return "Have you watched Guardians of the Galaxy?";
}

}
var output = chrisPratt(marvel);
console.log(output); // "I am Star-Lord!"

Enter fullscreen mode Exit fullscreen mode

Notice we used return multiple times and had to write the if…else statement and embed their values in curly brackets etc, which is great. But it can be shortened using ternary operators. The same code above will be evaluated as such in ternary operation;

var marvel = true;

function chrisPratt(marvel) {
  return (marvel === true) ? "I am Star-Lord!" : "Have you watched Guardians of the Galaxy?";
}
var output = chrisPratt(marvel);
console.log(output); // "I am Star-Lord!"
Enter fullscreen mode Exit fullscreen mode

Note: All variables used in a ternary operation should be defined before the operation is created.

One more thing, it is recommended not to nest ternary operators, because it may be difficult to understand.

Good programmers write code that humans can understand. So it will be great not to overuse these ternaries expressions, but use them in specific instances.

Ternary Operators may seem obscure or ambiguous for most developer and most people who don’t know, but it’s a great way to refactor your code. And with enough practice, you will be able to understand it whenever you see it in your code or other developer codes.

Top comments (10)

Collapse
 
mjworsley profile image
mjworsley

While coding, one of the key things I try to aim for is readability and maintainability - after all, the interpreter or compiler doesn't really care how many lines you've used, but you will care when you try to read it again 6 months later.

In my experience, the ternary operator prioritizes brevity over readability. If we take this to its logical extreme, we'd be naming all our variable 'a1', 'a2' etc...

Collapse
 
mrlarson2007 profile image
Michael Larson • Edited

I have the same feelings. I limit use of ternary operators where it makes sense to use them. Most of the time I use if statements. Reason? I want to opitimize for readability not brevity.

Collapse
 
swapnil7000 profile image
Swapnil7000

I have also written a blog on ternary operators please give your reviews on it.

Collapse
 
puritanic profile image
Darkø Tasevski

Ternary operators are not a shortcut nor replacement for If/else statements. Ternaries are okay when you need to return something based on condition, and you want to write it as oneliner. They are okayish in React too (as we can't use if/else in jsx). Besides this ternaries can get hard to read and hard to maintain pretty fast, so I think that overusing them would be a really bad idea.
There's even Eslint rule for disallowing nested ternaries 🙂

In the end, it's only important that a programmer knows what syntax to use in what situation.

Collapse
 
iandavid profile image
David Okpare

Yes, you're absolutely right! The article wasn't meant to "replace if statements", but shed light on it being a possible option for using conditional operators :) And thanks for highlighting the fact that it shouldn't be overused. I have included it in the post

Collapse
 
alainvanhout profile image
Alain Van Hout

There is a big difference between concise code and dense code. Widespread usage of ternary operators more often leads to the latter, which has a very detrimental effect on code maintainability.

Writing less characters isn't the same as writing better code.

Collapse
 
thomasjunkos profile image
Thomas Junkツ

But both sets overlap ;)

Collapse
 
alainvanhout profile image
Alain Van Hout • Edited

Only to a limited degree. The techniques tend to be quite different. In most cases, concise code involves a meticulous architecture, while dense code involves syntactical tricks.

Or to put it in another way: concise code is thoughtful, while dense code is 'clever' <shudder>.

Their respective goals are also quite different. Concise code optimizes for less logic and more semantics, while dense code optimizes purely for less characters and/or lines.

Collapse
 
thomasjunkos profile image
Thomas Junkツ • Edited

Ternaries as shown here are mostly fine.

I use them mostly to provide variables with (default) values which come in a binary flavor.

For functions I prefer


chrisPratt = (marvel)=>{
if(marvel) return "I am Star-Lord!";
return "Have you watched Guardians of the Galaxy?";
};

because your eyes rest on the condition and it is easy from that to look at the non matching case.

But I admit, this has more to do with personal taste ;)

You should add a warning sign not to overuse ternaries, esp. start nesting those guys. This could end up pretty nasty.

Collapse
 
iandavid profile image
David Okpare

Thanks for highlighting it. I have included it in the post.