JS · Lesson 3

Control Flow

Making decisions with if, else and switch

So far, every line of your code ran, from top to bottom. Real programs make choices: show an umbrella only when it rains, or a different section each day. In this lesson your code learns to decide.

What you'll learn

  • How to compare values and get true or false.
  • How to run code only when something is true, with if, else if and else.
  • How to pick one choice out of many with switch.

Welcome to decisions

Control flow is the order in which your code runs. With if, else and switch, you control it: some code runs only when a condition is true, and other code runs when it is false.

A condition is a question with a yes-or-no answer, like "is the rain chance above 50?". In JavaScript the answer is a boolean: true or false, which you met in JS Lesson 2.

Think of a jeepney driver at a traffic light. If the light is red, the driver stops (if). If it isn't red but it's yellow, the driver slows down (else if). For any other light, the driver goes (else). The driver checks in that order and does only one of them.

The checks happen from top to bottom. As soon as one is true, its code runs, and the rest are skipped.

A closer look

Comparing values

A comparison asks a question about two values and gives back true or false. > and < mean greater and less than, and >= and <= include the value itself. To ask "are these the same?", use three equals signs: ===. Its opposite is !==, "not the same". Remember that one = means "put this value in", from JS Lesson 2. The common mistakes below show what happens when they get mixed up.

How an if statement is written

The lines inside { } are called a block. They are indented two spaces, so you can see at a glance which lines belong to the if. JavaScript doesn't need the spaces, but people do.

Checking more than one thing

&& means and: both sides have to be true. || means or: one true side is enough. ! means not and flips true to false. So day === "Saturday" || day === "Sunday" is true on both weekend days.

switch: one value, many choices

When you compare one value against many exact choices, switch is easier to read than a long chain of else if. Each case is one choice. When the value matches, the code under it runs until a break. default is like else: it runs when no case matches.

switch checks for an exact match, like ===. For ranges, like "more than 70", use if and else if.

Let's build it

Let's make Front Page Bytes give weather advice and pick a section for each day. The HTML and CSS stay the same in every step: a heading and two boxes, #weather and #day. Watch the boxes and the console as the JavaScript changes.

Step 1: Ask true-or-false questions

Your code
let rain = 80;console.log(rain > 50);console.log(rain < 50);console.log(rain === 80);console.log(rain !== 80);
What you see

Console

    Nothing here yet. console.log() writes here.

    rain holds 80. Each line asks a question about it, and the console shows the answers: 80 is greater than 50 (true), not less than 50 (false), the same as 80 (true), and not "not the same" (false).

    Step 2: Run code only if something is true

    Your code
    let rain = 80;if (rain > 50) {  document.getElementById("weather").innerHTML = "Bring an umbrella!";}
    What you see

    Console

      Nothing here yet. console.log() writes here.

      rain > 50 is true, so the line inside the { } runs and the weather box says Bring an umbrella! Try picturing rain as 20: the condition would be false, and the box would keep its old text.

      Step 3: Do something else with else

      Your code
      let rain = 20;if (rain > 50) {  document.getElementById("weather").innerHTML = "Bring an umbrella!";} else {  document.getElementById("weather").innerHTML = "No umbrella needed today.";}
      What you see

      Console

        Nothing here yet. console.log() writes here.

        Now rain is 20, so the condition is false. The if block is skipped and the else block runs instead: No umbrella needed today. One of the two always runs, never both.

        Step 4: More choices with else if

        Your code
        let rain = 40;let message;if (rain > 70) {  message = "Heavy rain. Stay inside if you can.";} else if (rain > 30) {  message = "Light rain. Bring an umbrella.";} else {  message = "Clear skies today!";}document.getElementById("weather").innerHTML = message;
        What you see

        Console

          Nothing here yet. console.log() writes here.

          JavaScript checks from the top. 40 is not above 70, so the first block is skipped. 40 is above 30, so the else if block runs, and the rest is skipped.

          Each block puts its sentence in the message variable, and the last line shows it. This way the page is changed in one place only.

          Step 5: Pick one of many with switch

          Your code
          let day = "Wednesday";let section;switch (day) {  case "Monday":    section = "Tech news";    break;  case "Wednesday":    section = "Game reviews";    break;  case "Friday":    section = "App picks";    break;  default:    section = "Top stories";}document.getElementById("day").innerHTML = day + ": " + section;
          What you see

          Console

            Nothing here yet. console.log() writes here.

            switch (day) compares day with each case. It matches "Wednesday", so section becomes Game reviews, and break leaves the switch. If day were "Tuesday", no case would match, and default would give Top stories.

            Step 6: Share one answer between cases

            Your code
            let day = "Sunday";let section;switch (day) {  case "Saturday":  case "Sunday":    section = "Weekend edition";    break;  case "Monday":    section = "Tech news";    break;  default:    section = "Top stories";}document.getElementById("day").innerHTML = day + ": " + section;
            What you see

            Console

              Nothing here yet. console.log() writes here.

              case "Saturday": has no code and no break, so it falls through to the next case. That way Saturday and Sunday share one answer: Weekend edition.

              Quick notes

              > < === !== Comparing values
              rain > 50

              How to use

              • a > b Greater than.
              • a < b Less than.
              • a >= b Greater than or equal to.
              • a <= b Less than or equal to.
              • a === b Equal: the same value and the same type.
              • a !== b Not equal.

              Examples

              1. Is the player old enough?

                console.log(age >= 13);
              2. Is the answer right?

                console.log(answer === "Manila");
              if Run code only when true
              if (rain > 50) { console.log("Umbrella!"); }

              How to use

              • if (condition) { } Runs the code in { } only when the condition is true.
              • When the condition is false, JavaScript skips the { } and moves on.

              Examples

              1. Show a message only when a score is high.

                if (score > 90) {  console.log("Great job!");}
              else Otherwise
              } else { console.log("No umbrella."); }

              How to use

              • else { } Runs when the if before it was false.
              • It has no condition of its own and always comes last.

              Examples

              1. Pass or try again.

                if (score >= 75) {  console.log("You passed!");} else {  console.log("Try again.");}
              else if Check another condition
              } else if (rain > 30) { console.log("Light rain."); }

              How to use

              • else if (condition) { } Checks another condition when the ones before it were false.
              • You can have as many as you need. Only the first true one runs.

              Examples

              1. Pick a grade.

                if (score >= 90) {  grade = "A";} else if (score >= 80) {  grade = "B";} else {  grade = "C";}
              2. Greet by the time of day.

                if (hour < 12) {  greeting = "Good morning";} else if (hour < 18) {  greeting = "Good afternoon";} else {  greeting = "Good evening";}
              switch Pick one of many
              switch (day) { case "Monday": section = "Tech"; break; }

              How to use

              • switch (value) { } Compares one value with many cases.
              • case "x": The code to run when the value is "x".
              • break; Leaves the switch, so the next case doesn't run too.
              • default: Runs when no case matches.

              Examples

              1. A menu choice.

                switch (choice) {  case 1:    food = "Adobo";    break;  case 2:    food = "Sinigang";    break;  default:    food = "Rice";}
              && || ! And, or, not
              day === "Saturday" || day === "Sunday"

              How to use

              • a && b And: true only when both are true.
              • a || b Or: true when at least one is true.
              • !a Not: flips true to false and false to true.

              Examples

              1. Both must be true.

                if (age >= 13 && hasPermission) {  console.log("You can join.");}
              2. Either one is enough.

                if (day === "Saturday" || day === "Sunday") {  console.log("No classes!");}

              Common mistakes

              These are mistakes many beginners make. None of them shows an error, which makes them hard to spot. Each mini browser shows what really happens.

              Using = instead of ===

              The mistake
              let rain = 20;if (rain = 80) {  document.getElementById("weather").innerHTML = "Bring an umbrella!";} else {  document.getElementById("weather").innerHTML = "No umbrella needed today.";}console.log(rain);
              What you see

              Console

                Nothing here yet. console.log() writes here.

                rain = 80 doesn't compare. It puts 80 into rain, so the condition counts as true and the umbrella message shows, even though the rain chance was 20. The console shows the damage: rain is now 80.

                Tip: Compare with === (three equals signs). One = puts a value into a variable.

                Forgetting break in a switch

                The mistake
                let day = "Monday";let section;switch (day) {  case "Monday":    section = "Tech news";  case "Wednesday":    section = "Game reviews";    break;  default:    section = "Top stories";}document.getElementById("day").innerHTML = day + ": " + section;
                What you see

                Console

                  Nothing here yet. console.log() writes here.

                  The "Monday" case has no break, so the code keeps going into the "Wednesday" case. section is set twice, and Monday shows Game reviews.

                  Tip: End each case with break;, unless you want it to share the next case's code on purpose.

                  Checking in the wrong order

                  The mistake
                  let rain = 90;let message;if (rain > 30) {  message = "Light rain. Bring an umbrella.";} else if (rain > 70) {  message = "Heavy rain. Stay inside if you can.";} else {  message = "Clear skies today!";}document.getElementById("weather").innerHTML = message;
                  What you see

                  Console

                    Nothing here yet. console.log() writes here.

                    90 is above 30, so the first block runs and says Light rain. JavaScript stops at the first true condition, so the rain > 70 check never gets a turn.

                    Tip: Put the narrowest check first: test rain > 70 before rain > 30.

                    Test your knowledge

                    Write JavaScript in the JS tab. score and day are ready for you. Give a message for the score, like Excellent for 90 and up, then pick a club for the day with switch. Try changing score and day to test every choice.

                    No clicking needed. Each goal gets a check mark by itself once your code does it.

                    1. Use if to check the score. not done yet
                    2. Add an else if for another range of scores. not done yet
                    3. End with an else for every other score. not done yet
                    4. Show the result in #result. not done yet
                    5. Use switch with at least two cases to pick a club for the day, and show it in #club. not done yet
                    Your code
                    What you see

                    Console

                      Nothing here yet. console.log() writes here.

                      Go to Exercises

                      Recap

                      • Comparisons like >, <, === and !== give true or false. &&, || and ! combine them.
                      • if runs a block only when its condition is true. else if checks another condition, and else catches the rest. Only the first true block runs.
                      • switch compares one value with many cases. break ends each case, and default runs when nothing matches.

                      References

                      Lesson content prepared by the WebCore F.E. team for beginner learners. The following references were used in preparing this lesson.

                      • ECMA International. ECMAScript Language Specification (official specification). Open reference