Search

The Ternary Operator in Javascript

  • Share this:
post-title

First of all, let’s take a look at the syntax of a typical if statement:

if ( condition ) {
  value if true;
} else {
  value if false;
}

Now, the ternary operator:

condition ? value if true : value if false

Now, here’s what we all need to know:

  1. The condition is what you’re actually testing. The result of your condition should be true or false or at least coerce to either boolean value.
  2. ? separates our conditional from our true value. Anything between the ? and the : is what is executed if the condition evaluates to true.
  3. Finally a : colon. If your condition evaluates to false, any code after the colon is executed.

Let’s try this with an example – Person Status

let person = {
  name: 'Nana',
  age: 30,
  status: null
};
person.status = person.age >=16 ? 'Adult' : 'Minor';

Since 30 is greater than 16, this evaluates to true; and therefore, we get:

person.status = (true ? 'Adult' : 'Minor';)

Since the condition of our conditional is true, the value between the ? and : is returned. In this case, that is 'Adult'.

Enjoy!

Design | UX | Software Consultant
View all posts (125)