CSCI-1080 Intro To CS: Web Development

Saint Louis University
Department of Computer Science

Decisions and Loops

List of learning outcomes

By the end of this study session you will be able to:

  1. Make more elaborate decisions using if and else statements

  2. Make decisions using switch statements

  3. Create while loops

  4. Create do ... while loops

  5. Create for loops

If, Else and Else if

In the last section we have seen an IF statment. Here we elaborate a bit more on other code paradigms to make decisions. If and else are used in JavaScript (and in many other programming languages) like in english. You are lucky that your native language is English…

Consider this basic example:

<!doctype html>
<html>
  <head><script>
    var user_name;
    user_name=prompt("What is your name?");
    if (user_name == "Dave")
      alert("Great name!");
  </script>
  </head>
</html>

One observation is that there is only one line of code after the if statement. If I want to include more instructions I need to include them into curly braces as follows:

if (user_name == "dave" ) {
    alert("Great name!");
    awesome_name=true;
}

Braces are optional if there is only one line of code but not optional if we have at least two instructions separated by a ; (even if they are on the same line).

If ... else

As your intuition may tell, else goes at the end of the if and it handles any situation not already handled at that point. Example:

<!doctype html>
<html>
  <head><script>
    var user_name;
    user_name=prompt("In which state did you grow up?");
    if (user_name == "missouri")
      alert("Me too!");
    else
      alert("I grew up in another state");
  </script></head>
</html>

If ... else if

Let's extend that structure. Let's add an else at the end to capture the situation where they don't type in dave and they don't type in joseph.

We can use else if to add another logic test, and we can add as many logic test as we like, even though the more if else statements we have the more unreadable our code becomes. Example:

<!doctype html>
<html>
  <head><script>
    var user_name;
    user_name=prompt("What is your name?");
    if (user_name == "mary")
      alert("Great name!");
    else if (user_name == "joseph")
      alert("Pretty good name!");
  </script></head>
</html>

If ... else if

But what about if wasn't mary, and it wasn't joseph, all right we could do the third test. What about if it was none of those, then we can catch the situation where none of those tests was true, and we capture it with some kind of a message at the end, if all of those failed then we go to a else. For example:

<!doctype html>
<html><head><script>
  var user_name;
  user_name=prompt("What is your name?");
  if (user_name == "dave")
    alert("Great name!");
  else if (user_name == "jogesh")
    alert("Pretty good name!");
  else if (user_name == "oz")
    alert("Excellent name!");
else
    alert("Your name isn't great, never mind...");
</script></head></html>

Now, that's one way to handle a series of tests. Another way is switch. So, switch looks very different, but it's quite similar in the actual result of what it does.

Switch case

Let us assume we are checking something, mostly likely a variable name. Switch is another way to test but by jumping directly to the memory location of interests, without going over all possible tests. Example:

switch(variable_name) {
    case "option_1": do_something_1();
break; ... : ...
    case "option_n": do_something_n();
                     break;
}
default:  do_something_default();

To recall our previous example:

<!doctype html>
<html>
    <head>
        <script>
        var user_name=prompt("What is your name?");
        switch(user_name) {
            case "mary":
                alert("Great name!");
                break;
            case "joseph":
                alert("Pretty good name!");
                break;
            default:
                alert("this is shown if none of the previous case matches");
}
        </script>
    </head>
</html>

Okay, so what's this break? Well, this break stops any more tests being made. So, if the first check was true (name entered was mary), the instruction break tells the browser: “don't do any more checks”.

So break is used to stop any more case comparisons. Sometimes break is appropriate, sometimes it isn't. Let us show an example where we do not have break in every single test.

<!doctype html>
<html>
    <head>
        <script>
        var user_name=prompt("What country would you like to visit?");
        switch(user_name) {
            case "Mexico":
            case "Italy":
                alert("Take me also!");
                break;
            case "Japan":
            case "Philippines":
                alert("Great! Have fun!");
                break;
            case "North Korea":
                alert("Oh! Good luck!");
                break;
            default:
                alert("I am sure you will have a great time");
}
        </script>
    </head>
</html>

If you typed in any country except those five, the code catches that in the default and just gives a general response.

While Loops

Let us now look at loops in JavaScript, starting with the while loop. There is also a related structure called a do while loop. What is a loop? A loop simply repeats some code again and again, until a termination condition is encountered. A while loop is the simplest loop and this is its syntax:

while (condition) { ... some code goes here ...
};

Each time the loop content is executed we call it an iteration.

Let us consider the following code:

<!doctype html>
<html><head>
    <title>Example of while()</title>
    <script>
        var response, finished;
        finished=false;
        alert("I can really understand a bit of Javascript now.");
        while (!finished){
            response=prompt("Do you agree?");
            if (response.indexOf("y")==0)
}
    </script>
</head></html>

The while condition (inside the parenthesis) is some JavaScript code, perhaps or maybe a variable. if the condition is evaluated to true then the code inside the braces will be executed. When this code is finished, then it will come back up the top and it will check again, is the condtition still true? If it is, the code will be executed again. We have a so called loop pattern. Remember that exclamation mark, it means the opposite, right? It's the Not operator.

Note also that in the above example we used:

string.indexOf(“text”)

which gives you the location of the first “text” in the string. For example, if I write:

var text = “The cat's hat was wet”; result = text.indexOf(“at”);

“Do While” Loops

The loop pattern above will be executed again and again as long as the condition is true. However, it is possible that the particular pattern inside braces will never get executed. If I want to make sure that my loop is executed at least once before checking the condition I need to use a do while loop. Example:

<!doctype html>
<html><head>
    <title>Example of do .. while()</title>
    <script>
        var response, finished;
        finished=false;
        alert("Florence is a great city.");
        do {
            response=prompt("Do you agree?");
            if (response.indexOf("y")==0)
                finished=true;
        } while (!finished);
    </script>
</head></html>

Try to copy the code above into a real html page and test it yourself.

“For” Loops

When instead we know exactly how many times we want to run the loop, we use the for loop. The syntax of for loop is JavaScript is as follows:

for (initialization; test condition; iteration statement){
   Statement(s) to be executed if test condition is true
}

Example:

Try the following example to learn how a for loop works in JavaScript.

<html>
   <body>

      <script type="text/javascript">

            var count;

            document.write("Starting Loop" + "<br />");

            for(count = 0; count < 10; count++){
               document.write("Current Count : " + count );
               document.write("<br />");
            }

            document.write("Loop stopped!");

      </script>

      <p>Set the variable to different value and then try...</p>
   </body>
</html>




The contect of this site is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.