DevNotes
@devnotes ·
JavaScript Part 3: Making decisions with if
Code gets useful when it can choose: show an error if the password is too short, or give a discount if the cart is big enough.
if and else
JavaScript checks each condition from the top, runs the first block whose condition is true, and skips the rest. With 72, that's "Pass". Order matters here: if the >= 40 check came first, a 95 would print "Pass" too.
Combining conditions
&&(and): true only if both sides are true||(or): true if at least one side is true!(not): flips true to false and false to true
Truthy and falsy
An if doesn't need an actual true or false. You can give it any value, and JavaScript decides whether it counts as true. These count as false, and they're called falsy: false, 0, "" (an empty string), null, undefined and NaN.
Almost everything else is truthy, including "0", "false", an empty array [] and an empty object {}. That's why this works:
An empty string is falsy, so it prints the second message. Read if (city) as "if there's a city".
Be careful with numbers, though. A score of 0 is falsy too, so if (score) treats a real score of 0 as missing. When 0 is a valid answer, say what you mean: if (score !== undefined).
The ternary: a one-line if
When you just need to pick between two values:
Read it as: is stock above 0? If yes, "In stock". If not, "Sold out". It's great for short choices like this. For anything longer, a normal if is easier to read.
switch
For checking one value against a list of exact matches:
Don't forget break. Without it, JavaScript carries on and runs the next case's code too. Two cases stacked with nothing between them, like Sat and Sun here, share the same code on purpose.
Try it
Write the price check for a cinema ticket: under 3 is free, 3 to 12 is a child ticket, 60 and over is a senior ticket, and everyone else pays full price. Test it with 2, 3, 12, 30 and 60. The edges, 3, 12 and 60, are exactly where bugs hide.
Next: JavaScript Part 4: Repeat things with loops
Join WIK to like and reply to DevNotes and see more like this.