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;

Join the Lean Web Club! Coaching. Courses. Coding resources. Get the skills, confidence, and support you need to learn front-end web development and achieve long-term success.

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