DEV Community

loading...

Understanding JS Ternary Operators

Kiara Contreras
Web Developer / Cat Lover / Green Tea Witch / She/Her
Updated on ・2 min read

As a beginner dev, seeing code like this can be a tad bit, well, overwhelming.

let person = {
name: 'John',
age: 25,
legal: null
};

person.legal = person.age >= 21 ? 'Yes' : 'No';

overwhelmed

Not to worry! Conditional (Ternary) Operators can be easy to use and will simplify your code, even if it's just a little bit.

What do Ternary Operators represent?

Ternary Operators are used as a shorthand for if else statements. if else statements check a condition and usually have this syntax:

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

So, if I wanted to determine whether the above person was above the legal US age for drinking I could write an if else statement like so.

if (person.age >= 21) {
person.legal = 'Yes';
else {
person.legal = 'No';
}

In the example above I'm able to determine whether the person is legal and assign a value to person.legal. But we can also accomplish this by using the ternary operator! Below is the syntax:

condition ? value if true : value if false

Instead of using an if else statement let's return the the first example given.

person.legal = person.age >= 21 ? 'Yes' : 'No'

Here I'm assigning person.legal to be either Yes or No by checking their age. If person.age >= 21 then Yes is returned. Otherwise person.legal is set to No.

Things to know

  • The condition is what's being tested, whether it be an if else statement or ternary operator.
  • A ? separates the condition from the true value. Anything after the ? and the before the : is what is executed if the condition is true.
  • If the condition evaluates to false, any code after the colon is executed.

In conclusion, I appreciate you reading this and hope that you can now use ternary operators! Besides experience, I got most of my information from this awesome article which goes on to explain advanced ternary operators such as Nested Ternary and Multiple Ternary.

Discussion (0)