Conditionals
- if / else
- Logical operators
A function that always does the same thing is only half-wired. The other half is a decision: run this path, or that one, depending on what's true right now.
if / else: a fork in the circuit
if (temperature > 65) {
status = "warm";
} else {
status = "cool";
}if takes a condition in parentheses — anything that evaluates to
true or false, like the comparisons from the last lesson. If that
condition is true, the block right after it runs. If it's false,
JavaScript skips straight to else and runs that block instead.
Exactly one of the two branches ever fires — never both, never neither.
The else is optional. An if on its own just does nothing when the
condition is false, instead of running an alternative.
Combining conditions: &&, ||, !
Sometimes one comparison isn't enough. && ("and") is true only when
both sides are; || ("or") is true when at least one side is; !
("not") flips a true to false or a false to true.
if (temperature > 65 && isSunny) {
status = "perfect beach weather";
}That whole condition is only true when it's warm and sunny — drop
either one, and the branch doesn't fire.
Common mistake
Inside an if, a single = doesn't compare — it assigns, exactly
like lesson 1 warned. if (isOn = true) doesn't ask whether isOn is
true; it forces isOn to become true, and then treats that
(now-true) value as the condition — so the if branch always runs,
silently, no matter what isOn used to hold. Triple-check for ===
inside every condition you write.
You can now make a single decision. Next lesson gives you a list of values and a way to make that same decision — or run that same code — once for every item in it.
The lab has that decision waiting to be wired.