cult3

Javascript Control Flow Structures

Oct 29, 2012

Table of contents:

  1. If, Else, Else if
  2. Switch
  3. For
  4. For in
  5. While
  6. Do While
  7. Breaks
  8. Real life examples
  9. Conclusion

Control Flow Structures are an important aspect of programming languages that allow your code to take certain actions based on a variety of scenarios. Control Flow is a fundamental concept in programming that allows you to dictate how your code runs under different conditions or until a certain condition is met.

I find when I talk to newbie programmers, the importance of Control Flow Structures is often lost. A newbie programmer will want to replicate the functionality of Facebook or Twitter because they can only see the surface of what is going on. Control Flow Structures can seem a little bit abstract when you first start learning about them, but it is critical to understand the power of them.

This tutorial will focus on the most common Control Flow Structures you will encounter in Javascript. Control Flow is an important concept to learn in all programming languages, so the theory carries across multiple languages.

If, Else, Else if

Probably the most common Control Flow Structure you will encounter is some variety of the if, else, else if structure.

If

The if statement simply makes an evaluation and then does something depending on if the evaluation was true or false.

For example:

if (1 > 0) {
  alert("True");
}

In this example, we check if 1 is greater than 0. If it is, we pop an alert box.

We could also reverse it:

if (0 > 1) {
  alert("True");
}

This time we are asking if 0 is greater than 1. 0 is not greater than 1 so the alert box would never be called.

Else

The two examples above will do something if the statement evaluates to true, but what if we wanted to do something if it evaluates to false? Well, we could use the else clause.

if (0 > 1) {
  alert("True");
} else {
  alert("False");
}

In this example, the statement would evaluate to false and so we would move to the else clause and pop and alert that says “False”.

Else if

If we want to evaluate one statement, or evaluate a second statement, we could use else if.

if (0 > 1) {
  alert("0 is greater than 1");
} else if (9 > 3) {
  alert("9 is greater than 3");
}

In this example, the first statement would evaluate to false, but the second statement would be true so Javascript would only pop the second alert box. If neither of the statements evaluated to true, neither of the alerts would be called.

You can also use multiple if, else if and else statements within the same block.

if (23 > 34) {
  alert("23 is greater than 34");
} else if (45 > 65) {
  alert("45 is greater than 65");
} else {
  alert("None of the statements are true");
}

Operators

So far we’ve seen the > operator which means greater than.

Here are some more operators that you can use in your if statements.

Less than == equal to === equal to != Not equal to !== Not equal to

You might be wondering why there are two versions of “equal to” and “not equal to”. Javascript makes comparisons based on equality. The “==” will convert datatypes during this conversion to try and make this comparison, whilst “===” will not. This means that “==” can often give you weird results when it has made a datatype conversion in order to test equality, whereas “===” won’t make the conversion and so therefore it would be more accurate.

Generally, you should always use the “===” and the “!==” symbols.

The ! symbol simply means “not”. So “!==” is not equal to and “!true” is not true. You’ll see this quite often in Javascript and other programming languages.

Nesting

These structures can also be nested so that you can work under even more specific conditions.

var sky = "blue";
var grass = "green";
if (sky === "blue") {
  if (grass === "green") {
    alert("The sky is blue and the grass is green");
  }
}

All of the Control Structures in this tutorial can be nested within each other. Also, you can mix and match nested Control Structures to nest one into another. I’ll give you some real life examples at the end, just be aware that you aren’t restricted to using certain Control Structures.

And, Or

Nesting is often useful, but it can become tedious and overly complicated. To make things more simple, you can use the And && or Or || operators.

var sky = "blue";
var grass = "green";

// If the sky is blue AND the grass is green
if (sky === "blue" && grass === "green") {
  alert("The sky is blue and the grass is green");
}

// If the sky is blue OR the grass is green.
if (sky === "blue" || grass === "green") {
  alert("The sky might be blue and / or the grass might be green");
}

In the first statement, the alert box will only pop both conditions are true. In the second box, the alert will pop if either of the conditions are true.

Switch

Writing out lots of if statements can become a bit tedious if you have lots of possibilities. A simple way around this problem is to use a switch statement instead.

var trees = "green";

switch (trees) {
  case "purple":
    alert("Trees are purple");
    break;
  case "pink":
    alert("Trees are pink");
    break;
  case "green":
    alert("Trees are green");
    break;
  default:
    alert("Trees are an unknown colour");
}

So instead of writing 3 if statements and an else statement, we can just write a switch statement that reduces the amount of code we need to write. In this example, the switch statement evaluates the variable “trees” and runs code depending on what it equals. If it does not equal any of the supplied cases, it falls back to the default case.

For

When you want to do an action a number of times, you could simply write it, but this is tedious and impractical. The for loop allows you to run a piece of code as many times as you want without repeating yourself.

for (i = 0; i < 10; i++) {
  alert("Hello x " + i);
}

The for loop looks complicated, but it’s really very simple.

We’ll break it down, piece by piece.

i = 0;

First we need to set a count. This records the number of times that we loop through the structure so we can eventually stop. If you didn’t set a count, the loop would continue forever. Here we are setting i to 0.

i < 10;

Next we need to specify the condition for the loop. In this case we are saying “keep going as long as i is less than 10”.

i++;

And finally, the last bit is what to do on each loop. In this case we simply increment i by 1.

So first we set i to 0. We tell Javascript we want to keep looping through this structure as long as i is less than 10. Then every time we loop through the structure, we increase i by one. The result is the code within the for structure will be looped 10 times.

The same method can be used to get each element of an array.

Take this array for example:

var rappers = ["Kanye", "Jay Z", "Dr Dre", "Eminem"];

As we’ve seen in previous tutorials, arrays are Zero Indexed and so “Kanye” would be at position 0, and “Eminem” would be at position 3.

To print out the names of each rapper to the console, we could write:

// Find the number of items of the array
var length = rappers.length;

// Loop through the array
for (i = 0; i < length; i++) {
  console.log(rappers[i]);
}

First we set the count to 0. Next we want to keep looping through the array whilst the count is less than the length of the array. Remember we can find the number of items in an array by calling the length property. Next we increment the count by 1 on every loop. And finally we print each rapper by calling the array and passing the index value.

For in

When you want to loop through an Object, you can’t use a counter because the properties have names, not numbers.

Take this Object for example:

var cat = {
  name: "Francine",
  age: "2 months",
  colour: "grey",
};

In order to print the properties and the values from this Object, we could use the for in loop like this:

for (var property in cat) {
  console.log(property + ": " + cat[property]);
}

Here we are getting each property from the Cat Object. We can then access the value of each property using bracket notation and passing the property name.

While

The while loop is similar to the for loop in that it will keep running your code until a condition is satisfied. for loops are great if your code relies on counting or you are iterating through a known set of items, but sometimes you need to loop through something using a different conditional.

while loops can be used to do the same job as a for loop, but it means you have to write more code out.

// While
var i = 0;
while (i <= 100) {
  console.log(i);
  i++;
}

// For
for (i = 0; i <= 100; i++) {
  console.log(i);
}

It’s better to use while loops when you need to use a condition such as true or false.

var mySwitch = true;

while (mySwitch) {
    alert("I'll only bother you once");

    mySwitch = false;
}

In the example above, the while loop will keep looping whilst the switch is set to true.

Do While

The do while loop is similar to the while loop in that it will run your code until a condition is satisfied. However, the evaluation happens at the end of the loop, rather than the start, so your code will always run at least once.

var i = 0;

do {
  alert("i = " + i);
  i++;
} while (i < 100);

Breaks

If you want to stop a loop at a certain point, before the condition has been satisfied, you can use a break.

var log = ["Good", "Good", "Good", "Error", "Good"];
var length = log.length;

for (i = 0; i < length; i++) {
  if (log[i] === "Good") {
    console.log("System running ok");
  } else {
    alert("OMG there's an error!");
    break;
  }
}

In this example, we loop through the array and a print a message if the system is ok. But if there is an error in the log, we need to break out of the loop straight away and send an alert.

The result of running this code should be three “System running ok” messages and one “OMG there’s an error!” alert. The final “System running ok” is never run because we have broken out of the loop.

Real life examples

As I mentioned at the top of this post, Control Flow Structures can seem a bit abstract when you first learn about them. I’m sure you’re probably thinking, “How will this ever help me to create web apps?!”.

Here are a couple of examples that you might come across. These aren’t all perfect Javascript examples, rather, they show how you could theoretically deal with each problem in Javascript.

If

Check to make sure an email address has been entered in a form.

if (email === "") {
  alert("You need to enter your email address");
}

Else

If an email has been set, add it to an object, if it has not been set, send an alert.

if (email !== "") {
  person.email = email;
} else {
  alert("You need to enter your email address");
}

Else if

Check to see if an email has been set.

if (person.email !== "") {
    console.log(person.email);
} elseif (email !== "") {
    person.email = email
    console.log(person.email);
} else {
    alert("We can't find your email");
}

Nesting

Nest a for loop and an if statement so we only print out the indexes of an array that have a value.

var colours = ["red", "blue", "", "green"];
var length = colours.length;

for (i=0; i<length; i++) {
    if (colours[i] !== "") {
        console.log(colours[i]);
    }
}

And

Check that a username and a password have been set.

if (username !== "" && password !== "") {
  // Validate
}

Or

Check if the user has entered either their username or their email.

if (username !== "" || email !== "") {
  // Validate
}

Switch

Set admin rights depending on the user’s priveledges.

switch (userLevel) {
  case "admin":
    login = 1;
    break;
  case "user":
    login = 2;
    break;
  default:
    login = "guest";
    break;
}

For

Print all of the statuses from a timeline.

var timeline = ["I ate a sandwich", "Off to the party!", "What a nice day"];
var statuses = timeline.length;

for (i = 0; i < statuses; i++) {
  console.log(timeline[i]);
}

For in

Print out of the user’s detail on their profile.

for (var detail in user) {
  console.log(user["detail"]);
}

While

Show the first 100 tweets.

while (i <= 100) {
  console.log(tweets[i]);
  i++;
}

Do while

Show atleast the latest tweets.

var i = 0;

do {
    console.log(tweets[i]);
    i++;
} while(i < new);

Conclusion

Control Flow Structures are one of the fundamental elements of programming. Testing and evaluating conditions will be very important to achieve even the most simple results in programming. It’s an important concept to understand early on, because you will come across the need to use these building blocks all the time.

It’s also important to understand how each Control Flow Structure works, what are the benefits of each structure and when and where they should be used.

Hopefully the Javascript tutorials so far have given you a firm foundation and understanding of Javascript.

If you missed any of the tutorials, here is a quick review:

Philip Brown

@philipbrown

© Yellow Flag Ltd 2024.