RSRobince Studio

Ternary and Switch

The ternary operator is a one-line shortcut for an if/else that returns a value: condition ? a : b.

A switch statement is tidy when you compare one value against many fixed options.

const age = 20;
const label = age >= 18 ? "adult" : "minor";

switch (label) {
  case "adult": console.log("Welcome"); break;
  default: console.log("Hi");
}
Always add break in each case, or execution falls through to the next case.
Try it yourself

Loading editor…