JavaScriptLesson 6 of 16

Conditions: if, else and logic

A program gets clever once it can choose. A condition asks a yes-or-no question and runs the branch of code that fits.

Key points

  • if (…) { … } else if (…) { … } else { … }: checks run top to bottom until one fits
  • Compare with > < >= <= and the strict === and !==; prefer them to == and !=
  • && means and, || means or, ! means not
  • The ternary operator: condition ? valueIfYes : valueIfNo
  • 0, "", null, undefined and NaN count as false in a condition

Example

const temperature = 18;const isRaining = true; if (temperature > 25) {  console.log("Shorts weather");} else if (temperature > 15) {  console.log("A light jacket");} else {  console.log("Coat and scarf");} console.log(isRaining && temperature < 20 ? "Take an umbrella" : "No umbrella");console.log(5 === "5", 5 == "5", !isRaining);

18 is not above 25 but it is above 15, so the second branch ran. 5 == "5" is true because == converts types, while the strict === honestly says false.

Task

How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.

Finish ticketPrice(age, isTuesday): children under 6 go free (0), ages 6 to 17 and 65 or older pay 6, everyone else pays 10, or 7 on Tuesday. The program should print Kid: 0, Teen: 6, Adult: 10, Adult on Tuesday: 7 and Senior on Tuesday: 6.

Output

What your program prints appears here.