JavaScript if...else, Ternary and switch Statements
Conditionals let a program choose what to do. JavaScript offers three tools: the if statement for general decisions, the conditional operator for choosing between two values, and switch for comparing one value against a list of cases.
if, else if, else
The condition goes in parentheses and the code to run goes in braces. JavaScript evaluates the conditions in order and runs only the first block whose condition is truthy, then skips the rest. With hour = 14, the first test hour < 12 fails, the second hour < 18 passes, and "Good afternoon" is printed.
Braces are optional for a single statement, as in the last line of the example, but always using them avoids bugs when someone adds a second line later.
The conditional operator
condition ? valueIfTrue : valueIfFalse is an expression, so it produces a value you can store or print directly. It is the only JavaScript operator with three operands, which is why people call it "the ternary". Use it for short choices; nesting several of them quickly becomes unreadable.
Expected output
Good afternoon minor Weekend Please type something
switch
switch (value) compares the value against each case using strict equality (===). Execution starts at the first matching case and continues downward until a break. That "fall-through" behavior lets several cases share code, as "sat" and "sun" do in the example, but it also means a forgotten break runs the next case's code too. The default case runs when nothing matches.
switch reads well for a handful of fixed values. For mapping many keys to results, an object lookup such as const labels = { sat: "Weekend" } is often shorter.
Truthiness in conditions
Conditions do not need to be booleans. Any value is converted using the truthy and falsy rules from the operators chapter, so if (!input) is true for an empty string. Be careful when 0 is a valid value: if (!count) treats zero like "missing". Write if (count === undefined) when you mean that.
Common mistakes
- Writing
if (x = 5), which assigns instead of comparing and is always truthy. - Forgetting
breakin aswitchcase. - Expecting
switchto use loose equality;case "1"does not match the number1.
Summary
if/else if/elseruns the first block whose condition is truthy.cond ? a : bchooses between two values in an expression.switchuses===, falls through untilbreak, and has an optionaldefault.
Quiz: if, else and switch