Summary

In this lesson, you learned that:

  • The if statement runs its block of code only if its condition is true. There is no semicolon after if (...).
  • else adds a second branch, which runs when the condition is false, and else if adds more branches with conditions of their own. The program checks the conditions from top to bottom and runs only the first true one, so their order matters.
  • Comparison operators compare two values: ===, !==, >, <, >= and <=. Two texts are equal only if they match exactly.
  • = assigns a value, while === compares. Use === and !==, not == and !=.
  • Every comparison gives a boolean value, true or false, which you can print, store in a variable and use as a condition.
  • Logical operators combine conditions: && (and) is true when both parts are true, || (or) when at least one is, and ! (not) turns true into false and back. Parentheses group conditions; without them, && goes before ||.
  • An if statement can be nested in the block of another if. Indent every block so that you can see what belongs where.

Next comes a small project, in which you'll try out everything from the first two lessons on your own. Then, in the lesson on arrays, you'll learn to store many values in a single variable, such as a shopping list or the scores of a whole class.

Instructions

Practice: a zoo ticket costs 150. Children under 6 get in for free, children under 18 pay 80, and seniors aged 65 or more pay 100. Above the last line, write an if statement with else if branches that changes price to 0, 80 or 100. With an age of 15, the program prints Ticket price: 80.

Check the youngest visitors: change age to 4. The program must print Ticket price: 0. If it prints Ticket price: 80, look at the order of your conditions.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

13/13

Next