Course

Ternary Operator

Loading...

In this lesson, you'll learn about the in JavaScript, a concise way to perform simple checks.

Ternary Operator

You could say that the statement is a more complex version of the statement. There's yet another version of it: the ternary operator.

It should be used just for simple checks.

To explain the ternary operator , let's first take a look at the syntax of a typical statement:

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

Now, the ternary operator:

condition ? value if true : value if false

Although this is just pseudocode, meaning the code is written in half English and half real syntax, I think you can still see how we would use the . Let's use the same old driver's license example we had when we were learning about the statement .

if (person.age > 18) {
    console.log('You can drive');
} else {
    console.log('You may not drive yet');
}

And now let's transfer it to a . I'll first write it out and then we're going to explore it in detail:

person.age > 18 ? console.log('You can drive') : console.log('You may not drive yet');

How It Works

  • Reading from left to right, we first have our .
  • Following a question mark , is the expression that is going to be executed if the condition evaluates to .
  • Finally, following the colon sign , is the expression that is going to be executed if the condition evaluates to .

At first, may seem a bit weird and hard to read. But as you write more of them, you'll quickly get better at understanding them. They'll quickly become your go-to tool if you have just a simple or question.

Loading...

0 Comments

"Please login to view comments"

glass-bbok

Join the Conversation!

Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.

Upgrade your account
tick-guideNext Lesson

'for' and 'while' Loops