BTG Coding School

Conditions

Last time we looked functions, which let you give names to chunks of code for later reuse. While our current set of programming tools is quite versatile, it is still lacking in one major way.

Our programs will always run through the same series of steps each time we run it. While running the program saves us time, each run of the program gives us essentially the same result.

Our programs will be able to handle many more scenarios if they can make decisions. Then, rather than simply running straight through, we can imagine our program following a flowchart based on what it encounters.

In programming, this is called conditional logic, or branching.

Introducing the if statement

The most basic form of conditional logic is the if statement. You can think of it as being equivalent to the English phrase: “If CONDITION, then do STATEMENTS.” Here’s an example in Javascript:

// We call 'a > b' here the condition. This is
// some code that must evaluate to either true or false
if (a > b) {
  // The code between these curly braces
  // only runs if the condition evaluated to true.
  console.log('a is bigger');

  // Like other curly braces, this creates a new scope,
  // so we can define local variables in here as with functions.
}
// Any code afterwards runs both if the 
// condition is matched, and if it isnt.

Similar to functions, if changes which steps the program runs. First, Javascript evaluates the code in those parentheses, our “condition”. If it is true, it will run everything inside that “branch”. If not, it just skips to after the brace.

else if, else

Sometimes we want to run code only if the condition is not matched. We can use the keyword else, right after the if, to accomplish this:

if (a == 1) {
    console.log('a is one');
} else {
    console.log('a is not one');
}
console.log('finished checking conditions');

And finally, we often want to handle a series of conditions:

if (a < 4) {
    console.log('a is very negative');
} else if (a < 0) {
    console.log('a is slightly negative');
} else if (a > 0) {
    console.log('a is positive');
} else {
    console.log('else: a must be zero');
}

Conditions are checked, one at a time, only as long as all the previous conditions have returned false. Once a true condition is reached, that branch is run and no other branches will be checked. The else case is run only if all conditions return false.

You can use as many else if blocks as required.

A complete set of programming tools.

Now that you have learned to use conditions, you can write programs to compute anything that can be computed. We can say that the piece of Javascript you now know is Turing Complete.

But programming is only partially about getting the right result, and the rest is about building programs that can be understood easily by yourself and others. There are still a few more Javascript features that will be quite useful in practice.

Exercises

This time, I’ll give you a few exercises with solutions, as well as a few ideas for programs you can work on independently.

  1. Write a function (maximum) that takes in two numbers, and gives us whichever number is larger.
  2. The absolute value of a number is its distance away from zero. The absolute value of a positive number is the same as the number, while the absolute value of a negative number is the opposite of the number. Write your own function, my_abs(num), to compute this. Note: Javascript provides you Math.abs, but you should be able to write your function without using this.
  3. (Challenge). Write a flow-chart version of this comic The arrows represent input from a user. The diamond shapes represent the questions you ask the user. The arrows represent possible user input. I recommend you create functions for each of the diamond blocks, so that you can just call the function rather than repeating certain decisions.
  1.  
    function maximum(a, b) {
      if (a > b) {
        return a;
      }
      return b;
    }
    // You might have also written
    function maximum(a, b) {
      if (a > b) {
        return a;
      } else {
          return b;
      }
    }
    
  2.  
    function my_abs(num) {
      if (num < 0) {
        return -num;
      }
      return num;
    }
    
  3.  
    // Note, this solution utilizes recursion, which we'll discuss more in a future lesson.
    
    function pick_random() {
        console.log('pick_random');
        let tried = prompt("Try a new one at random. Are there any buttons you havent tried? y or n");
        let ok = tried === "y";
        if (ok) {
            click_it();
        } else {
            google_program();
        }
    }
    
    function google_program() {
      console.log('google_program');
      console.log('Google it');
      did_it_work();
    }
    
    function did_it_work() {
      console.log('did_it_work');
      let worked = prompt("Did it work? y or n");
      let yes = worked === "y";
      if (yes) {
        done();
      } else {
        trying_30_min();
      }
    }
    
    function done() {
        console.log("You're done!");
    }
    
    function click_it() {
      console.log('click_it');
      alert('click it.');
      did_it_work();
    }
    
    function trying_30_min() {
      console.log('trying_30_min');
      let trying_30 = prompt("Have you been trying for > 30 minutes? y or n");
      let timeout = trying_30 === "y";
      if (timeout) {
        console.log('As someone for help or give up.');
      } else {
        start();
      }
    }
    
    function start() {
      console.log('start');
      let found_button = prompt("Do you see a button related to what you want to do? y or n");
      let found = found_button === "y";
      if (found) {
        console.log('You found one. Click it.');
        click_it();
      } else {
        console.log("You can't find one.");
        pick_random();
      }
    }
    function xkcd_flowchart() {
      start();
    }
    

Project ideas

The independent projects will require a bit more code, so I recommend you save and edit the Javascript template from earlier.

  • Find another flowchart for something you are interested in, and write a program using conditionals that implements it. See the number 3 exercise for an example.

  • Dart scoring. Write a program to tell the user how many points were scored for a single dart throw. Ask 1) which number was the outer edge for that slice. 2) Whether it was in the outermost double section, or the triple section, or either of the bulls-eye sections. Full rules

  • Blackjack score calculator. Let a user enter their current sum of cards, and a single letter that represents a new card. Let them use k, j, q, or a for the face cards, and a number for the other cards. Tell them their current value, and whether or not they “busted”. Rules on Wikipedia

Next up: loops

Next we’ll learn how to use loops in Javascript, which is a way of repeating code. Then we’ll see how functions actually already let us do this :)