Skip to content
Lesson 6 of 15

Step 1 of 6 · Reading · ~3 min

Learn

Control Flow

Conditionals: if, else if, else

Programs have to choose. By the end of this lesson you can express a decision as an if ladder, combine conditions with && and ||, and place the checks so that boundary values land in the right branch.

if, else if, else

javascript

JavaScript tests the conditions from the top, runs the first branch whose condition is true, and skips the rest. The else branch is the fallback when nothing matched. Exactly one branch runs.

Because the first match wins, each later condition only has to describe what is left. Here temp < 100 really means "above 0 and below 100", since the <= 0 case was already taken. Order the checks so each one narrows the remaining cases, and test the special or invalid cases first.

Comparing

javascript

Always use === and !==. The two-character == converts types behind your back (0 == "" is true); a later lesson shows the full mess. Note the difference between < and <=: boundary values (exactly 0, exactly 100) are where almost every conditional bug lives.

Combining conditions

javascript

&& and || stop as soon as the answer is known, and they return one of their operands, not necessarily true or false: "" || "guest" is "guest", and "Ada" && "ok" is "ok".

Truthy and falsy

if accepts any value and treats it as true or false. Exactly seven things are falsy: false, 0, -0, "", null, undefined, NaN. Everything else is truthy, including "0", "false", [] and {}.

javascript

A frequent bug: const qty = given || 1; meant "default to 1", but it also turns a legitimate 0 into 1. Be explicit: given !== undefined ? given : 1. (Modern JavaScript has ?? for exactly this, but it, like ?., is a SyntaxError on the Node version that runs this course's exercises, so we avoid it.)

The ternary

For choosing between two values:

javascript

Read it as "if temp > 30, then "hot", else "mild"". Do not nest ternaries; use an if ladder.

switch

When one value is compared against many exact options, switch is tidier:

javascript

Each case needs a break, or execution falls through into the next case. Stacking labels as above is the one deliberate use of fall-through.

Common mistakes

  • Writing the broad check first. In a ladder that tests age < 65 before age < 13, everyone under 65 hits the first branch and the specific branches never run.
  • Using < where <= is meant, so the boundary value falls into the wrong branch.
  • if (x = 5): a single = assigns and the condition is always truthy. Comparisons need ===.
  • Forgetting break in a switch, so two cases print.
  • Treating [] as false; an empty array is truthy.

Your exercise

Classify an age. The starter reads the number. Decide which cases must be checked first, and decide each boundary carefully.

Up nextLoops: for and whileControl Flow

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…