Decisions in JavaScript (Summary)

At the start of this course, your scripts ran every line, every time. Now they make choices. Your ticket checker takes two answers exactly as a visitor typed them, rejects the ones it can’t price, and picks one price from a published rule table, including the boundary ages where mistakes like to hide. You also explained why it works, which is the part that lets you change it with confidence.

What You Can Do Now

Each skill below showed up first in a small script and then came back in the ticket checker:

  • Run code only sometimes: An if block runs only when its condition is truthy, and the code after the closing brace always runs. A name you declare inside the braces is gone after them, so you declare it before the if, as tip-mistake.js showed.
  • Choose one path: In an if … else if … else chain, the first true branch wins and JavaScript skips the rest. That’s why branch order matters for overlapping conditions, and why age < 16 and age >= 65 put each visitor in exactly one row.
  • Pick the right shape: Separate if statements suit things that can all apply. An else if chain picks at most one (exactly one when it ends in else), and a nested if asks a question that matters only after another one, like the wind check in pack.js that counts only when it’s raining.
  • Combine conditions: && checks a range or a rule with several parts, || accepts several values, and ! turns a condition around. Because && stops at the first falsy value, it can guard a risky step, such as checking for null before calling a method.
  • Clean and check text: trim() and toLowerCase() turn " Yes " into "yes" before you compare it. Methods like includes() and slice() look inside text: includes() answers with a Boolean, slice() gives you a new string, and neither one changes the original.
  • Check input before you use it: You know which values are falsy, when ?? keeps a real 0 that || would replace, and how to reject a missing, blank, or non-numeric answer, in that order. Number.isNaN() after Number() lets a baby’s age of 0 through, which if (Number(answer)) wouldn’t.

If one of these still feels shaky, go back to its lesson and rerun the script with a value of your own. A boundary value, such as 16 in ticket.js, is usually the most revealing one to try.

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.