Conditionals and Loops

In this lesson of the JavaScript tutorial, you will learn...
  1. To write if - else if - else blocks.
  2. To write switch / case blocks.
  3. To return values from functions.
  4. To work with loops in JavaScript.

Conditionals

There are two types of conditionals in JavaScript.

  1. if - else if - else
  2. switch / case

if - else if - else Conditions

Syntax
if (conditions) {
 statements;
} else if (conditions) {
 statements;
} else {
 statements;
}

Like with functions, each part of the if - else if - else block is contained within curly brackets ({}). There can be zero or more else if blocks. The else block is optional.

Comparison Operators
Operator Description
== Equals
!= Doesn't equal
=== Strictly equals
!== Doesn't strictly equal
> Is greater than
< Is less than
>= Is greater than or equal to
<= Is less than or equal to
Logical Operators
Operator Description
&& and (a == b && c != d)
|| or (a == b || c != d)
! not !(a == b || c != d)

The example below shows a function using and if - else if - else condition.

Code Sample: ConditionalsAndLoops/Demos/IfElseifElse.html

<html>
<head>
<title>JavaScript Conditionals Demo</title>
<script type="text/javascript">
 function checkAge(){
  var age = prompt("Your age?", "") || "";
  
  if (age >= 21) {
   alert("You can vote and drink!");
  } else if (age >= 18) {
   alert("You can vote, but can't drink.");
  } else {
   alert("You cannot vote or drink.");
  }
 }
</script>
</head>
<body style="text-align:center">
<h1>JavaScript if - else if - else Demo</h1>
<h3>Age Check</h3>
<form>
 <input type="button" value="Age Check" onclick="checkAge();">
</form>
</body>
</html>
Code Explanation

The display of the page is shown below.

When the user clicks on the Age Check button, the following prompt pops up.

After the user enters his age, an alert pops up. The text of the alert depends on the user's age. The three possibilities are shown below.

Compound Conditions

Compound conditions are conditions that check for multiple things. See the sample below.

if (age > 18 && isCitizen) {
 alert("You can vote!");
}

if (age >= 16 && (isCitizen || hasGreenCard)) {
 alert("You can work in the United States");
}

Short-circuiting

JavaScript is lazy (or efficient) about processing compound conditions. As soon as it can determine the overall result of the compound condition, it stops looking at the remaining parts of the condition. This is useful for checking that a variable is of the right data type before you try to manipulate it.

To illustrate, take a look at the following sample.

Code Sample: ConditionalsAndLoops/Demos/PasswordCheckBroken.html

<html>
<head>
<title>Password Check</title>
<script type="text/javascript">
 var USER_PASS = prompt("Password:", ""); //ESC here causes problems
 var PASSWORD = "xyz";
</script>
</head>

<body>
<script type="text/javascript">
 if (USER_PASS.toLowerCase() == PASSWORD) {
  document.write("<h1>Welcome!</h1>");
 } else {
  document.write("<h1>Bad Password!</h1>");
 }
</script>
</body>
</html>
Code Explanation

Everything works fine as long as the user does what you expect. However, if the user clicks on the Cancel button when prompted for a password, the value null will be assigned to USER_PASS. Because null is not a string, it does not have the toLowerCase() method. So the following line will result in a JavaScript error.

if (USER_PASS.toLowerCase() == password)

This can be fixed by using the typeof() function to first check if USER_PASS is a string as shown in the sample below.

Code Sample: ConditionalsAndLoops/Demos/PasswordCheck.html

<html>
<head>
<title>Password Check</title>
<script type="text/javascript">
 var USER_PASS = prompt("Password:", "") || "";
 var PASSWORD = "xyz";
</script>
</head>

<body>
<script type="text/javascript">
 if (typeof USER_PASS == "string" && USER_PASS.toLowerCase() == PASSWORD) {
  document.write("<h1>Welcome!</h1>");
 } else {
  document.write("<h1>Bad Password!</h1>");
 }
</script>
</body>
</html>

Switch / Case

Syntax
switch (expression) {
case value :
 statements;
case value :
 statements;
default :
 statements;
}

Like if - else if - else statements, switch/case statements are used to run different code at different times. Generally, switch/case statements run faster than if - else if - else statements, but they are limited to checking for equality. Each case is checked to see if the expression matches the value.

Take a look at the following example.

Code Sample: ConditionalsAndLoops/Demos/SwitchWithoutBreak.html

<html>
<head>
<title>Switch</title>
<script type="text/javascript">
 var QUANTITY = 1;
 switch (QUANTITY) {
 case 1 :
  alert("QUANTITY is 1");
 case 2 :
  alert("QUANTITY is 2");
 default :
  alert("QUANTITY is not 1 or 2");
 }
</script>
</head>
<body>
 Nothing to show here.
</body>
</html>
Code Explanation

When you run this page in a browser, you'll see that all three alerts pop up, even though only the first case is a match. That's because if a match is found, none of the remaining cases is checked and all the remaining statements in the switch block are executed. To stop this process, you can insert a break statement, which will end the processing of the switch statement.

The corrected code is shown in the example below.

Code Sample: ConditionalsAndLoops/Demos/SwitchWithBreak.html

<html>
<head>
<title>Switch</title>
<script type="text/javascript">
 var QUANTITY = 1;
 switch (QUANTITY) {
 case 1 :
  alert("QUANTITY is 1");
  break;
 case 2 :
  alert("QUANTITY is 2");
  break;
 default :
  alert("QUANTITY is not 1 or 2");
 }
</script>
</head>
<body>
 Nothing to show here.
</body>
</html>

The following example shows how a switch/case statement can be used to record the user's browser type.

Code Sample: ConditionalsAndLoops/Demos/BrowserSniffer.html

<html>
<head>
<title>Simple Browser Sniffer</title>
<script type="text/javascript">
 switch (navigator.appName) {
 case "Microsoft Internet Explorer" :
  alert("This is IE!");
  break;
 case "Netscape" :
  alert("This is Mozilla!");
  break;
 default :
  alert("This is something other than IE or Mozilla!");
 }
</script>
</head>
<body>
 Nothing to show here.
</body>
</html>
Code Explanation

The navigator object, which is a child of window, holds information about the user's browser. In this case we are looking at the appName property, which has a value of "Microsoft Internet Explorer" for Internet Explorer and "Netscape" for Mozilla-based browsers (e.g, Navigator, Firefox).

Loops

There are several types of loops in JavaScript.

  • while
  • do...while
  • for
  • for...in

while Loop Syntax

Syntax
while (conditions) {
 statements;
}

Something, usually a statement within the while block, must cause the condition to change so that it eventually becomes false and causes the loop to end. Otherwise, you get stuck in an infinite loop, which can bring down the browser.

do...while Loop Syntax

Syntax
do {
 statements;
} while (conditions);

Again something, usually a statement within the do block, must cause the condition to change so that it eventually becomes false and causes the loop to end.

Unlike with while loops, the statements in do...while loops will always execute at least one time because the conditions are not checked until the end of each iteration.

for Loop Syntax

Syntax
for (initialization; conditions; change) {
 statements;
}

In for loops, the initialization, conditions, and change are all placed up front and separated by semi-colons. This makes it easy to remember to include a change statement that will eventually cause the loop to end.

for loops are often used to iterate through arrays. The length property of an array can be used to check how many elements the array contains.

for...in Loop Syntax

Syntax
for (var item in array) {
 statements;
}

for...in loops are specifically designed for looping through arrays. For reasons that will be better understood when we look at object augmentation, the above syntax has a slight flaw. If the Array class is changed, it is possible that the for...in loop includes more items than what you anticipated.

To be on the safe side, we suggest that you use a more verbose syntax as seen below.

Syntax
for (var item in array) if (array.hasOwnProperty(item)) {
 statements;
}

The hasOwnProperty() call will ensure that the item is indeed an element that you added to the array, not something that was inherited because of object augmentation.

Code Sample: ConditionalsAndLoops/Demos/Loops.html

<html>
<head>
<title>JavaScript Loops</title>
<script type="text/javascript">
 var INDEX;
 var BEATLES = [];
 BEATLES["Guitar1"] = "John";
 BEATLES["Bass"] = "Paul";
 BEATLES["Guitar2"] = "George";
 BEATLES["Drums"] = "Ringo";
 var RAMONES = ["Joey", "Johnny", "Dee Dee", "Mark"];
</script>
</head>

<body>
<h1>JavaScript Loops</h1>
<h2>while Loop</h2>
<script type="text/javascript">
INDEX = 0;
while (INDEX < 5) {
   document.write(INDEX);
   INDEX++;
}
</script>

<h2>do...while Loop</h2>
<script type="text/javascript">
INDEX = 1;
do {
   document.write(INDEX);
   INDEX++;
} while (INDEX < 5);
</script>

<h2>for Loop</h2>
<script type="text/javascript">
for (var INDEX=0; INDEX<=5; INDEX++) {
 document.write(INDEX);
}
</script>

<h2>for Loop with Arrays</h2>
<ol>
<script type="text/javascript">
for (var INDEX=0; INDEX<RAMONES.length; INDEX++) {
 document.write("<li>" + RAMONES[INDEX] + "</li>");
}
</script>
</ol>

<h2>for...in Loop</h2>
<ol>
<script type="text/javascript">
for (var instrument in BEATLES) if (BEATLES.hasOwnProperty(instrument)) {
 document.write("<li>Playing " + instrument + " there is " + BEATLES[instrument] + "</li>");
}
</script>
</ol>
</body>
</html>
Code Explanation

The sample above shows demos of all the aforementioned loops.

Conditionals and Loops Conclusion

In this lesson of the JavaScript tutorial, you learned to work with JavaScript if-else if-else and switch/case conditionals and several types of loops.

To continue to learn JavaScript go to the top of this page and click on the next lesson in this JavaScript Tutorial's Table of Contents.

Use of this website implies agreement to the following:

Copyright Information

All pages and graphics on this Web site are the property of Webucator, Inc. unless otherwise specified.

None of the content on this website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of web pages

This content may not be printed or saved. It is for online use only.


Linking to this website

You may link to any of the pages on this website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

This website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).

For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm.