Skip to main content Accessibility Feedback

Variables & Functions

Ternary Operator

A shorter way to write if...else statements. It has three parts:

let someVar = [the condition] ? [the value if true] : [the value if false];

It’s the equivalent of this.

let someVar;

if ([the condition]) {
	someVar = [the value if true];
} else {
	someVar = [the value if false];
}

Let’s say we wanted to define answer as num if num is greater than 10. If not, we’ll use 42.

let num = 0;
let answer = num > 10 ? num : 42;

Preorder my new course on Web Components! Want to learn how to build Web Components from scratch, master best practices, and more? Preorder today and get $100 off of the launch price.


Find this useful? You can support my work by purchasing an annual membership.