JavaScript Conditionals for Pythonistas (Summary)

Ruth’s race-day call now runs in JavaScript. With Finish the Race-Day Call done, race-day-call.js prints the same four lines as race_day_call.py on the main morning, from “Saturday morning race: racing (good racing wind)” to “Waiting for the race officer to confirm”.

Her rules carried over in their order because JavaScript also takes the first true branch. The shape changed because JavaScript doesn’t read indentation. Keep these JavaScript ways handy when you port your next decision-heavy script:

  • Write } else if (...) { with each branch in braces, and declare let decision; and let reason; above the chain. A const or let declared inside a branch ends at its brace, where a Python name outlives the chain.
  • Give a const variable one of two values with the conditional operator, condition first: startHour < 12 ? "morning" : "afternoon". It drops into ${} the way a conditional expression does in an f-string.
  • Combine conditions with &&, ||, and !, as in decision === "racing" && !officerConfirmed. Add parentheses when you mix && and ||, and negate a whole comparison with !== or !(...).
  • Check a range with two full comparisons, 6 <= windKnots && windKnots < 25.
  • Ask about one of several values with ["thunder", "fog"].includes(forecast), and about emptiness by size: warnings.length > 0, or Object.keys(settings).length === 0 for a plain object used as a record.
  • Match one value with switch, end every case body with break, stack the labels of cases that share a body above it, and catch the rest with default.
  • When each case only picks a value, look it up instead: COURSE_FOR[direction] ?? "short windward-leeward". An object also answers for inherited keys such as "toString", but the lookup is safe because direction only ever holds a compass code.

Typing elif or and out of habit stops the file with a SyntaxError. So does using not before a name, as in if (not officerConfirmed), or writing a conditional expression in Python’s order. Those mistakes at least announce themselves.

Ask Whether It Answers the Question You Mean

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.