Conditional operator in JavaScript

How do you use the ? : (conditional) operator in JavaScript? And where to use this operator?

Last updated:7/19/2021 5:29:37 AM

1 Answers

Ethan Karla
Ethan Karla

Basically for one word if else condition we use ternary operator. This is a one-line shorthand for an if-else statement and It's also known as the conditional operator.

Here is an example of code that could be shortened with the conditional operator:

var userType;

if (userIsYoungerThan18) {
  userType = 'Minor';
} else {
  userType = 'Adult';

This can be shortened with the ?: like so:

var userType = userIsYoungerThan18 ? 'Minor' : 'Adult';

Hope this information has cleared your confusion.

Happy Coding!