From the course: Learn JavaScript: Write Modern Code with JavaScript ESNext

Unlock this course with a free trial

Join today to access over 25,000 courses taught by industry experts.

Learn about ternary operators in JavaScript

Learn about ternary operators in JavaScript

- The last control flow related syntax we're going to cover for the moment is something called the ternary operator. This is, again, something that many other programming languages have, but it's still worth taking a look at JavaScript's take on it. So the ternary operator is sort of like an abbreviated version of an if statement that we can use as part of larger statements. The basic syntax is like this, we have some sort of Boolean condition followed by a question mark, and then two different values separated by a colon. Now, the trick here is that if the first Boolean statement is truthy, the whole ternary statement evaluates to the first value. If it's falsey, it evaluates to the second value. Now, the nice part about this comes when we want to assign one of two different values to a variable depending on some condition in our program. Without the ternary operator, we'd have to do something like this where we define a new variable without assigning it any value, and then use an if…

Contents