Sikau

JavaScript · Day 16 · about 25 min

Shorter decisions

The ternary and switch.

Two shortcuts

Sometimes a full if/else feels like a lot of typing for a tiny choice. And sometimes you have a long list of exact matches. JavaScript has a tool for each.

The ternary: ? and :

The ternary picks between two values in one line: condition ? valueIfTrue : valueIfFalse.

const age = 20;
const label = age >= 18 ? "adult" : "child";
console.log(label);

const momos = 1;
console.log(`${momos} ${momos === 1 ? "momo" : "momos"}`);

Use the ternary for choosing a value. For doing several things, a normal if/else is easier to read.

The rest of this lesson

  • switch: matching exact valuesexplain
  • Choosing the right decision toolexplain
  • Predict the outputpredict
  • A missing breakpredict
  • Your turnwrite code
  • Switch it upwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 68 lessons of JavaScript