JavaScript course · Part 2: Logic · lab 2 of 11
Decisions and repetition
Choosing between paths with if and else, guard clauses that keep code flat, picking a value without a long if, and going through a list without writing the same line twice.
By the end you can
- Write conditions that read like sentences
- Return early instead of nesting four levels deep
- Pick a value with a ternary or a lookup rather than a long chain
- Go through a list and do something with each item
Easier if you did first
step 1 of 4
Making a decision
if runs a block only when a condition is true. else runs when it is not. else if adds another question in between.
The conditions use comparison operators: === and !== for equal and not equal, then < > <= >= for sizes. Combine them with && meaning and, || meaning or, and ! meaning not.
Two habits make conditions readable. Put the thing you are asking about on the left, as you would say it aloud: if (guests >= 20). And give a complicated condition a name by putting it in a const first, so the if reads as a sentence.
Order matters when the conditions overlap. JavaScript takes the first one that is true, so the narrowest case has to come first. Check for over 100 before checking for over 20, or everything over 100 is caught by the earlier branch.
Write the delivery fee rule on the right.
const isLargeOrder = guests >= 50;
if (isLargeOrder) {
fee = 0;
} else if (guests >= 20) {
fee = 50;
} else {
fee = 100;
}
=== !== < > <= >= comparisons
&& || ! and, or, notWhat these words mean
- if / else if / else
- Run a block depending on a condition. The first true one wins.
- &&
- And: both sides must be true.
- ||
- Or: either side will do.
- !
- Not: turns true into false.
- block
- The code between curly brackets that runs together.
Easy to get wrong
if (guests > 20) before if (guests > 100)
The narrowest case first
200 guests is also more than 20, so the first branch catches it and the second never runs. The code looks right and quietly gives the wrong answer.
if (x = 5)
if (x === 5)
One equals sign assigns rather than compares, so the condition is always true and x has been changed as a side effect. It is a classic and the cause can take an hour to find.
What we check
- A large order is free
- A medium order is 50
- A small order is 100
- The boundaries are right, including exactly 50 and exactly 20
- You used an if
Nothing printed yet. Run your code.