Branching

Normally our programs flow line-by-line, in which the commands flows from the first line and goes downwards (known as being Sequential). The first lines runs first, then the second line, then the third line, etc. Branching is when we manipulate this flow in a different way. For example when we call a function it goes to the function and back to the normal flow of the program. In this section we will go over several different ways to branch: loops, if/else statements, and conditions.


Conditions are expressions that will come out as either true or false. This comes from comparing two items which will turn out as either true or false. Remember that the assignment operator is "a = b"(a is b), to compare two items we use either "a == b"(does a equal b?). Or we can use "a === b"(is a strictly equal to b?). Here is a list of comparison operators:

  • a == b - ( a is equal to b )
  • a === b - ( a is strictly equal to b [JS will not try and change data types temporarily] )
  • a != b - ( a is not equal to b )
  • a > b - ( a is greater-than b )
  • a < b - ( a is less-than b )
  • a >= b - ( a is greater-than or equal to b )
  • a <= b - ( a is less-than or equal to b )
var x = 3;
var y = 2;
alert(x==y); // --> false;
alert(x != y); // != means NOT EQUALS --> true
alert(x > y); // --> true;
alert(x < y); // --> false;
var y = "3";
alert(x===y); // num(3) == str("3") --> false;
alert(x==y) // num(3) == [num(3)] --> true;


== and === are not the same. == will filter you data-types so they are the same while JavaScript is in the process of comparison, while === will not. So different datatypes will never be the same using ===.

The most basic branch is the IF STATEMENT. Which will run a code if the statement is true, otherwise will not run the code if the statement is false. The code that the IF statement executes is between two brackets. Here is an outline:

if( condition ){ // <-- Start IF
   // Code that runs if condition is true.
} // <-- End IF.

Here is some example code:

var x = 5;
if(x == 5){
   alert("x is 5"); // x is 5 => true. So the alert statement will run.
}

Here is an example of a if statement that does not run.

var x = 10;
if(x < 10){
   alert("x is less than 10"); // (10 < 10) => false. So the alert statement will not run.
}
alert("End");

A add-on to the if statement is an IF-ELSE Statement. It will run the code in the if statement when the condition is true, otherwise if the condition is false it will run the code in the else statement:

if( condition ){
   //Code to run on condition is true
} else {
   //Code to run on condition is false
}

And here is some example code:


function checkEvenOdd(num){
   if(num%2 == 0){ // Remember '%' means Modulus (division remainder). 
      alert(num+" is even"); // If num%2 is 0 it means the number is even.
   } else {
      alert(num+" is odd");
   }
}

checkEvenOdd(7); // 7 is odd
checkEvenOdd(12); // 12 is even

Finnally we have the IF-ELSE IF-ELSE statement. You can think of it as a stack of if statements with an else at the bottom. Checking through a list of conditions and running unique code based on which condition we have met. Note that the else if part can be repeated, here is an outline:

if( condition1 ){
   // Code for condition1 is true
} else if( condition2 ){
   // Code for condition2 is true, if condition 1 was false.
} else {
   // If all the conditions were false run this.
}

And here is some example code (Note : This uses a Object to get the current time in hours)

var time = new Date().getHours(); // time is the current hour of the day from( 0 to 23)
if(time < 12){
   alert("Good morning!");    // From mid-night to 11AM. 
} else if(time <= 16){
   alert("Good afternoon!");  // From noon to 4PM
} else if(time <= 20){ 
   alert("Good evening!");    // From 5PM to 8PM
} else {
   alert("Good night!");      // From 9PM to 11PM
}

Another branch structure that has very similar functionality as the if-else if-else stucture is the Switch-Case structure. Here is an outline and it will be explained below:

switch( variable ) 
{
case 1:
  // Execute block if (variable === 1)
  break;
case 2:
  // Execute block if (variable === 2)
  break;
default:
  // Execute code if all cases fail 
}

Switch-Case uses a variable to compare to and checks the strict equality of that variable to each case. In this case if the variable is 1 then the first block will execute. The default is like the else in the if-type structures, such that if all cases are false then default will run. break is to exit some block of code early. It is used in this case so it does not run into other cases (since code is naturally sequential) .

For a better understanding lets put a if-else if-else structure next to a switch-case that do the same thing:

switch( x ) 
{
case "one":
  alert("x is one");
  break;
case "two":
  alert("x is two");
  break;
default:
  alert("x is not one or two.");
}
 
if(x === "one")
   {
   alert("x is one");
   } 
else if(x === "two")
   {
   alert("x is two");
   }
else
   {
   alert("x is not one or two");
   }

In programing loops are blocks of code that repeat. Arrays almost always use loops to go through them, for example lets say we have an array:

// How would we go through this?
var myArray = ["one","two","three","four","five"]; 

We could always write and output it line-by-line, but that would be cumbersom, definitely for large arrays.

output( myArray[0] );
output( myArray[1] );
output( myArray[2] );
output( myArray[3] );
output( myArray[4] );

The first loop we will talk about is the FOR loop:

for( init ; condition ; step ){
   // Code Block.
}
  • init: Code ran at the start of the loop (often defining a variable).
  • condition: Condition to check to run the loop, if true run the loop.
  • step: Code ran at the end of each iteration of the loop (often changing variable).

A for loop goes through init and checks condition, at the end of the loop it goes through step, and then condition again. If condition is true go through the loop again. The solution to the problem above would be using a for loop:

for(var i=0; i<myArray.length; i++){
   output( myArray[i] );
}
one two three four five

A simpler to write and read loop exclusively for going through arrays or objects is the for-in loop:

for( item in myArray ){
   output( myArray[item] );
}

This gives the same output as the normal for loop above.


You can also place a for loop inside of a for loop, this is known as a nested for loop. For example let's say we have a 2D array(an array within an array), known as a matrix in mathmatics. We would use nested for loops to get every element:

var myTable = [
      [1,2,3],
      [4,5,6],
      [7,8,9]
];
for( item in myTable){
   for( subItem in myTable ){
      output( myArray[item][subItem] );
   }
}
1 2 3 4 5 6 7 8 9

output() is not a function in JavaScript, I'm using it as a theodical function to show output. So we don't have so many alerts, a way to replace these examples is using: console.log() instead. This will output to the console of the browser.

Another common loop is the while loop, in which will repeat some block of code as long as some condition is true:

while( condition ){
   //Block of code that runs while condition is true.
}

So for example we could do something similar to a for loop using the while loop

var list = [1,2,3,4,5];
var i = 0;
while(i < list.length){
   output(list[i]);
   i++;
}
1 2 3 4 5

As you can see we are doing exactly what we do in a for loop but more manually. The while loop is often used when we don't know how many times the loop will repeat, while the for loop is used when we know exactly how many times the loop will repeat.


A infinite loop is a loop that never stops. And is when the condition in a loop is never false, you will mostly want to avoid infinite loops as much as possible. Here are two examples of infinite loops mistakes:

var list = [1,2,3,4];
for(var i = 1; i!=4; i+=2){
   output(list[i]);
}
2 4 error error error error error error ...

The first problem we notice is (i!=4), notice i will be: 1,3,5,7,9,... So it will always not be 4, this causes our infinite loop. It's much safter to use less-than or greater-than.

while(true){
   alert("hello");
}
hello hello hello hello hello hello ...

In this case the condition will always be true, unless we break out of the loop within the block of code inside the loop it will be an infinite loop. Although it does not mean it will always be an infite loop, we could use a break statement, for example:

var num = 0;
while(true){
   num += 2;
   if(num>=12){ break; }
   output( num );
}
2 4 6 8 10

  • Conditions: Are statements that can evaulate to be ethier true or false.
  • Branches are pieces of code that mainpluate the flow of the program:
    • IF Statement
    • ELSE-IF statement
    • IF-ELSE IF-ELSE statement
    • *break statement
  • Loops: Are segments of code that are repeated
    • FOR loops
    • WHILE loops
  • Infinite Loops: are loops that never stop.
Spencer Wieczorek