DEV Community

Cover image for JavaScript Ternary Operator
Lorenzo Zarantonello for This is Learning

Posted on

JavaScript Ternary Operator

JavaScript list of operators containing question marks might surprise new developers approaching the language for the first time. 
We already discussed how the nullish coalescing operator (??) works. 
In this post, we will talk about the conditional operator, also known as the ternary operator.

JavaScript Ternary Operator

Following MDN definition, "The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy".

condition ? expression1 : expression2
Enter fullscreen mode Exit fullscreen mode

You can read this operator as follow: IF the condition is true execute expression1 else execute expression2.

This is not entirely accurate but before diving into truthy and falsy let's see an example with a condition that can only be true or false.

let condition = true;
console.log(condition ? 'exp 1' : 'exp 2'); // exp 1
Enter fullscreen mode Exit fullscreen mode

Since we defined a variable called condition as true, the ternary operator executes the first expression which is a simple string "exp 1". 

The console.log() around the ternary operator logs the result of the ternary operator and it logs "exp 1".
This is the core concept of the ternary operator.

Ternary operator with truthy and falsy

As I said above, you can read this operator as follow: IF the condition is true execute expression1 else execute expression2. But this is not entirely accurate!

So, what is the problem?

When talking about Javascript Ternary Operator, MDN talks about truthy and falsy instead of true and false.

condition ? expression1 : expression2
Enter fullscreen mode Exit fullscreen mode

IF the condition is truthy execute expression1 else (falsy) execute expression2.

In simple terms, 

  • Truthy values are equal or can be converted to true. Which values are truthy? All values unless they are defined as falsy. Thanks…
  • Falsy values are equal or can be converted to false. (i.e. false, 0, -0, 0n, "", null, undefined, and NaN).

Image description

See some more examples using the ternary operator with strings and numbers.

Top comments (10)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

In this post, we will talk about a conditional operator called the ternary operator.

Typo? This sentence should read "In this post, we will talk about a ternary operator called the conditional operator."

Collapse
 
lorenzojkrl profile image
Lorenzo Zarantonello

This operator is called Conditional (ternary) operator in MDN: developer.mozilla.org/en-US/docs/W...

Conditional operator is actually correct but somehow it became less common than ternary operator. I just preferred to follow the most popular way.
Thanks for the feedback :)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Yes, but your sentence refers to it as a conditional operator. It's called the "conditional operator" and it is a ternary operator because it takes 3 operands (similarly, binary operators take 2 operands, unary operators take one).

It is commonly referred to as the ternary operator because JS only has the one operator like this that takes 3 operands.

Thread Thread
 
lorenzojkrl profile image
Lorenzo Zarantonello

Updated! Thanks for the feedback!

Collapse
 
johnpalmgren profile image
John Palmgren

Nice post. It took me a while to get round to learning about the ternary operator and now I use it all the time

Collapse
 
marynarzswiata profile image
MarynarzSwiata.pl

const age = 23;
const status = age >= 18 ? 'You are adult!' : 'You are not adult!';

It is valuable to say that this is for one-liners purpose.

Collapse
 
peerreynders profile image
peerreynders • Edited

It is valuable to say that this is for one-liners purpose.

That is missing the point.

The value of the conditional operator is that it is an expression, so it can be used anywhere where a value is needed (because expressions always have to evaluate to a value - even if that value is undefined).

if...else is a statement:

const age = 23;
let status = 'You are not adult!';
if(age >= 18) status = 'You are adult!';
Enter fullscreen mode Exit fullscreen mode
  • With if...else the else is entirely optional. With the conditional operator an alternate expression/value has to be supplied.
  • Here status can't be const bound because the if may need to change it.

const still can't be used here:

const age = 23;
let status;
if(age >= 18) status = 'You are adult!';
else status = 'You are not adult!';
Enter fullscreen mode Exit fullscreen mode

Without the conditional operator you have to resort to using functions in order to const bind status:

const age = 23;
const isAdult = () => age >= 18;
const status = myIf(isAdult, makeAdultStatus, makeYouthStatus);

function myIf(conditionFn, trueFn, falseFn) {
  if (conditionFn()) return trueFn();

  return falseFn();
}

function makeAdultStatus() {
  // ... some expensive status generation
  return 'You are an adult!';
}

function makeYouthStatus() {
  // ... some expensive status generation
  return `You aren't an adult!`;
}

console.log(status);
Enter fullscreen mode Exit fullscreen mode

Expressions versus statements in JavaScript

I find that people don't tend to use the conditional operator until they clearly understand the difference between statements and expressions.

a statement is a line of code commanding a task

  • the if statement changes the value that is bound to status
  • the conditional operator produces the new status value based on the existing age value.

That's a different way of thinking - similar to using .map() or .filter() to create a new array from an existing array.

Collapse
 
lorenzojkrl profile image
Lorenzo Zarantonello

Excellent addition!

Collapse
 
lorenzojkrl profile image
Lorenzo Zarantonello

Yes usually yes! That is a good practice to maintain some clarity.
I often end up calling some functions or passing some variables instead of having simple expressions/strings.

I added an example with some functions here: medium.com/@lorenzozar/javascript-...

Collapse
 
kodydev profile image
Kody

a good reminder, thanks!