JavaScript - Ternary Operator | DevsDay.ru

IT-блоги JavaScript - Ternary Operator

dev.to 25 мая 2021 г.


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

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

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

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;
}

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

🖐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);
}

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

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

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

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

Источник: dev.to

Наш сайт является информационным посредником. Сообщить о нарушении авторских прав.

tutorial javascript beginners webdev