Skip to main content
← ⚑ JavaScript & the browserΒ·Module C5 Β· Lesson 2
TaskWrite format(x) that returns: x.toFixed(2) for numbers, x.toUpperCase() for strings, "yes"/"no" for booleans, "unknown" otherwise. Log format(3.14159), format("hi"), format(true), format(null).

Narrowing with if + typeof

100 XP8 min
Theory

What is narrowing

A parameter can arrive as many types. Narrowing is splitting your code into branches per type so each branch only handles ONE shape.

function format(x) {
  if (typeof x === "number") return x.toFixed(2);
  if (typeof x === "string") return x.toUpperCase();
  if (typeof x === "boolean") return x ? "yes" : "no";
  return "unknown";
}

Inside each if branch the value is guaranteed to be that type. Editors with TypeScript-aware tooling (VS Code's JS server, JetBrains) will auto-complete the right methods inside each branch β€” no .ts file required.

The "fall through" guard

Always end with a default branch that handles "everything else". It's documentation: "I thought about other types, here's what happens."

πŸ”’

Sign up to start coding

Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial β€” card required, cancel anytime.

Sign up β€” free trial β†’

First 10 lessons in each track are free. No card needed for those.

← PreviousNext lesson β†’

Get one Python or web tip a day β€” by email

Short, hand-written, no spam. Unsubscribe in one click.