Search⌘ K
AI Features

The Ternary Operator

Explore the ternary operator as a concise alternative to the if/else statement in JavaScript and TypeScript. Understand how it returns values consistently, supporting functional programming principles, and learn the importance of readable, value-returning expressions.

The if/else statement

Let’s see how this statement works:

We all have choices to make. This is why all programming languages offer some variation of the if/else statement.

C++
function choices(thirsty) {
if (thirsty) {
return 'beer';
} else {
return 'hamburger';
}
}
console.log(choices(true));

The code snippet above prints beer when thirsty is true and hamburger when thirsty is false.

Note: Some languages are very strict about their booleans. For example, Java and C# would require a boolean for thirsty and reject anything else. Other languages, like Python and JavaScript, are true to their dynamic nature. They are more ...