Conditionals: The ternary operator

The ternary operator, a short way to express conditionals, and it works in this way:

<condition> ? <expression> : <expression>

The <condition> is evaluated as a boolean, and upon the result, the operator runs the first expression if the condition is true.

Or it runs the second expression if the condition is false.

In other words:

isTrue ? /* do this */ : /* do that */

Example usage:

const running = true
(running === true) ? console.log('stop') : console.log('run')

In this example we check if running equals to true, and if this is the case we call the stop() function. Otherwise we call the run() function.

Lessons in this unit:

0: Introduction
1: Comparison operators
2: `if` statements
3: How to use `else`
4: `switch`
5: ▶︎ The ternary operator
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!