Ternary Operators In JavaScript
Tags: javascript, beginners, webdev, productivity
Published: 2018-08-27 17:06:29

---
title: Ternary Operators In JavaScript
published: true
description: 
tags: #javascript, #beginners, #webdev, #productivity
---

*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!"

```

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!

```

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
```

**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!"
```

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!
```

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!
```

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!')
);
```

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"
```

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!"

```


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!"
```

> 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.**