DEV Community

loading...

JavaScript - Ternary Operator

César
Software Developer
・6 min read

It seems that some juniors overlook or eschew few JavaScript features because of its bizarre and dynamic nature. It's common to happen. I can relate to this evasive moment when I first began my journey as a web developer.

Back in my days, I preferred being explicit to being implicit when I was learning a new programming language. To be explicit means to have the intentions of glossing over concepts, practical examples etc. It is important to overcome that fear, which hinders you from exploring and experimenting with new things. Being implicit keeps you plain and aware of the curves that language has got.

It is healthy to break that comfort zone and try out some crazy features that a programming language hands over to you. Breaking that comfort zone would teach you lots of things you have never expected before.

Let's break it and have a clear understanding of JavaScript's feature ternary operator 🕵🏻‍♂️.

This article assumes you know at least a small percentage of JavaScript. You will learn what a ternary operator is. You will understand how to use this feature. And whether it is healthy or not to use it. Let's get started👌🏻.

What is a ternary operator?

A ternary operator is a shorthand version of the conditional statement. We are conscious that conditional statements take decisions based on what segments of code dictate to them to do. That's how they function. If the condition meets the demands, the decision-maker evaluates to true. But, if the condition doesn't meet the demands, it evaluates to false.

Suppose that we write a simple condition that checks out if a user is authorized or not🔑. Let's take a quick example:

const username = 'John';

if (username === 'John') {
  log(`Welcome back ${username}`);
} else {
  log(`Oops! ${username}, you are not authorized!`);
}

// expected output: Welcome back John
Enter fullscreen mode Exit fullscreen mode

Note that a real life example wouldn't be like this. It would be much more complex regarding authorization. So this is just for demo purposes only.

Now, if the variable username matches the condition username === 'John', then it evaluates to true which means that the user is authorized. If it doesn't match, the condition evaluates to false indicating that the user is not authorized.

🖐Oh, by the way, a quick note to explain extra few things concerning the block of code above. Using backticks might seem new to you. They are called Template literals or sometimes Template strings. Instead of using ordinary quotation marks which do not allow us to embed expressions, we can use template literals that allow us to embed expressions using ${expression}. For a deeper investigation, try MDN Documentation Template Literals. Great!👌🏻 Let's go on.

So that's what a simple conditional statement could do. Now back to the ternary operator. This latter is shorter than the original conditional statement. It takes three operands hence ternary. Let's take a look at its syntax:

// condition ? expression1 : expression2
Enter fullscreen mode Exit fullscreen mode

Wow, wait what? Yes, that's a feature JavaScript offers to use when necessary. Remember! The key phrase here is when necessary Let's see a practical example, supposing that we want to check navigation status:

const status = 'online';

status === 'online' ? log('ONLINE') : log('OFFLINE');

// expected output: ONLINE
Enter fullscreen mode Exit fullscreen mode

As you can see, this ternary operator can be divided into three parts, also known as operands. It takes a condition which checks out whether the status equals online or not.

The condition should always be followed by a question mark ( ? ). After declaring the question mark, we add the two expressions, which happen to be separated by a colon ( : ). If the condition is truthy, the first expression executes. If it turns out a falsy expression, then the second expression executes.

That's how a basic ternary operator operates. It's like asking a simple question: is the status online? Is it? If it is, do this job; if it is not, do this job.🔥

Boolean based conditions

It is not uncommon to trip over conditionals that will either evaluate thoroughly to true or false when using functions. But wait! Didn't we mention that conditions evaluate either to true or false by default? Yes, the case here is functions turn this feature to their advantage. Let's take an example, supposing that we have a simple function that compares values and returns either true or false.

function compare(x) {
  return x > 0 ? true : false;
}
Enter fullscreen mode Exit fullscreen mode

Did you locate the ternary operator? Yes, we can treat it like that. And guess what? That's fine to JavaScript's logic.🧐 Let's test that function and log out the result that's the returned value.

function compare(x) {
  return x > 0 ? true : false;
}

log(compare(10));
// expected output: true

log(compare(-10));
// expected output: false
Enter fullscreen mode Exit fullscreen mode

🖐By the way, if you're wondering what that log() function is. It's not a built-in function in JavaScript. It's just a shortcut for console.log() so that we don't have to type the entire thing every time. Here it is:

function log(val) {
  console.log(val);
}
Enter fullscreen mode Exit fullscreen mode

Default parameters

Here's another cool thing about ternary operators. We can use them to set default parameters. Just like this:

function comments(c) {
  c = typeof c !== 'undefined' ? c : 'Not yet';
  log(c);
}

comments();
// expected output: Not yet

comments('I like that pizza!🤤');
// expected outcome: I like that pizza!🤤
Enter fullscreen mode Exit fullscreen mode

So what is happening here is that we are checking if the function returns a value or not. If the function is invoked without a given value, it should return undefined by default. We would rather avoid such pitfalls. Ternary operators allow us to avoid such absurd behaviour by setting a static default parameter. If no value is provided, then the default will always be assigned to 'Not yet'.

Note that the ternary operator is not the only way to set default params. It's just to make it clear it's possible through the ternary operator.

🖐Note quickly that typeof is an operator that returns the data type. For a deeper investigation, check out MDN Documentation typeof Operator.

Healthy or not healthy?

Now how far do you think we can go with ternary operators? We can go deeper as this can become a nightmare later☠️. We can make an entire spiderweb nested by exploiting multiple conditions the same way it works with nested conditional statements. Let's peek into the original conditional that normally resorts to if … else if … else if … else.

Let's suppose we want to enter a student name and check whether that student was present or absent yesterday. A simple and passive checker to check out a particular student based on the student's name as a variable.

const studentName = 'Lisa';

if (studentName === 'Tom') {
  log('P');
} else if (studentName === 'Ann') {
  log('P');
} else if (studentName === 'Bob') {
  log('A');
} else if (studentName === 'Maria') {
  log('P');
} else if (studentName === 'Lisa') {
  log('A');
} else {
  log('Student does not exist');
}

// expected output: A
Enter fullscreen mode Exit fullscreen mode

That already looks daunting let alone using a ternary operator😱:

const studentName = 'Lisa';

studentName === 'Tom'
  ? log('P')
  : studentName === 'Ann'
  ? log('P')
  : studentName === 'Bob'
  ? log('A')
  : studentName === 'Maria'
  ? log('P')
  : studentName === 'Lisa'
  ? log('A')
  : log('Student does not exist');

// expected output: A
Enter fullscreen mode Exit fullscreen mode

Yes, we can create that spiderweb🕸️. And it looks like infinite hell. We usually separate the conditions by colons. Although it might seem intelligible now, it can become confusing when using it in a larger code environment.

So is it healthy?

It is not recommended to fall back on this behaviour. Not only is it a bad practice, but it's also giving a bad impression about yourself as a developer. We should write code that's readable and accessible to the entire team.

It is not healthy to use this behaviour. However, it is healthy to use ternary operators wisely and only when necessary. That key phrase, remember? It is a blessing. It can be a curse, too.

Thank you for your attention. I hope it has been as informative as you expected.

Instagram: @cesarcode.init

Github: cesarcode-init

Discussion (7)

Collapse
jonrandy profile image
Jon Randy • Edited

A ternary operator is a shorthand version of the conditional statement

Not quite...

A ternary operator is simply an operator that takes 3 operands. It just so happens that JavaScript (and some other languages) only have one operator of this type - which is the conditional operator. It's often referred to as 'the' ternary operator as the language has no other operators with this number of operands.

Similarly, unary operators take 1 operand - examples being !, ~, and the unary + - and binary operators take - you guessed it - 2 operands!

Collapse
cesar_code profile image
César Author

I appreciate your feedback.😀

However, I always have to remind myself that this article is intended for beginners who are still struggling with logic etc. Remaining as simple as possible is mandatory.

With that being said, "A ternary operator is a shorthand version of the conditional statement" isn't entirely my own formulation. It's universally recognized as, and I quote from MDN Documentation Conditional Ternary Operator, an operator which is frequently used as a shortcut for the if statement.

Doesn't it seem that it's an alternative or rapid way of representing the IF statement?🤔 This doesn't mean it should replace it altogether.

You might have read it subjectively, but we are all on the same page at the end of the day as your comment repeats what I clarified in the article. But truly appreciated 🙏.

Collapse
peerreynders profile image
peerreynders • Edited

Doesn't it seem that it's an alternative or rapid way of representing the IF statement?🤔

Strictly speaking no given that a conditional operator is part of an expression - while if is a statement:

  • the if statement conditionally executes a block of statements (or a single statement) - it does not return a value
  • the conditional operator has to return a value - so there always has to be an expression used for a "truthy" condition and another for a "falsy" condition - it's impossible to formulate a valid conditional operator without an else value - something that is fairly standard with an if statement.

Expressions versus statements in JavaScript

an if statement cannot become the argument of a function.

Knowing that you'd likely write your example as:

const status = 'online';

console.log(status === 'online' ? 'ONLINE' : 'OFFLINE');
Enter fullscreen mode Exit fullscreen mode

i.e. using the conditional operator to select the value to pass to console.log() rather than having it evaluate a void function.

Thread Thread
cesar_code profile image
César Author

Thank you for the article. It's interesting! Appreciated🙏.

Collapse
oskarcodes profile image
Oskar Codes

Quick tip when you defined your log function, you could’ve just writen

const log = console.log;
Enter fullscreen mode Exit fullscreen mode
Collapse
cesar_code profile image
César Author • Edited

I love it! Thank you!

The function being referred to in this course takes the explicit road. I wanted it to be beginner friendly. But, I usually do it this way:

const log = (x) => console.log(x);
Enter fullscreen mode Exit fullscreen mode

I think I found an alternative haha thanks!🙏

Collapse
oskarcodes profile image
Oskar Codes

Well it’s not exactly a perfect alternative, as your solution won’t accept multiple parameters, like this:

console.log("Hello", "World");
Enter fullscreen mode Exit fullscreen mode

But mine will.