Conditionals and Loops
- To write if - else if - else blocks.
- To write switch / case blocks.
- To return values from functions.
- To work with loops in JavaScript.
Conditionals
There are two types of conditionals in JavaScript.
- if - else if - else
- switch / case
if - else if - else Conditions
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.
| 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 |
| 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>
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>
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
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>
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>
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
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
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
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
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.
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>
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.
