Conditionals

Contact Us or call 1-877-932-8228
Conditionals

Conditionals

There are two types of conditionals in JavaScript.

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

if - else if - else Conditions

The structure of an if - else if - else condition is shown below:

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

Note the difference between == (equals) and === (strictly equals). For two objects to be strictly equal they must be of the same value and the same type, whereas to be equal they must only have the same value. See the code sample below:

Code Sample:

ConditionalsAndLoops/Demos/StrictlyEquals.html
---- C O D E   O M I T T E D ----

	<li>Equals:
		<ul>
			<li>0 == false:
				<script type="text/javascript">
					document.write(0 == false);
				</script>
			</li>
			<li>0 == "":
				<script type="text/javascript">
					document.write(0 == "");
				</script>
			</li>
			<li>5 == "5":
				<script type="text/javascript">
					document.write(5 == "5");
				</script>
			</li>
		</ul>
	</li>
	<li>Strictly Equals:
		<ul>
			<li>0 === false:
				<script type="text/javascript">
					document.write(0 === false);
				</script>
			</li>
			<li>0 === "":
				<script type="text/javascript">
					document.write(0 === "");
				</script>
			</li>
			<li>5 === "5":
				<script type="text/javascript">
					document.write(5 === "5");
				</script>
			</li>
		</ul>
	</li>
---- C O D E   O M I T T E D ----

Open this file in your browser to see that all of the value pairs are equal, but none is strictly equal: The use of equals versus strictly equals in the browser.

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 an if - else if - else condition:

Code Sample:

ConditionalsAndLoops/Demos/IfElseifElse.html
---- C O D E   O M I T T E D ----

<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>
---- C O D E   O M I T T E D ----

<form>
	<input type="button" value="Age Check" onclick="checkAge();">
</form>
---- C O D E   O M I T T E D ----

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:

Also notice the use of the default operator (||) in the checkAge() function. The default operator was covered in the "JavaScript Operators" activity of the "Variables, Arrays and Operators" lesson. If you don't remember how it works, feel free to go back and review it.

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
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Password Check</title>
<script type="text/javascript">
	var userPass = prompt("Password:", ""); //ESC here causes problems
	var password = "xyz";
</script>
</head>
<body>
<script type="text/javascript">
	if (userPass.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 userPass. Because null is not a string, it does not have the toLowerCase() method. So the following line will result in a JavaScript error:

if (userPass.toLowerCase() == password)

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

Code Sample:

ConditionalsAndLoops/Demos/PasswordCheck.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Password Check</title>
<script type="text/javascript">
	var userPass = prompt("Password:", "") || "";
	var password = "xyz";
</script>
</head>
<body>
<script type="text/javascript">
	if (typeof userPass == "string" && userPass.toLowerCase() == password) {
		document.write("<h1>Welcome!</h1>");
	} else {
		document.write("<h1>Bad Password!</h1>");
	}
</script>
</body>
</html>

Switch / Case Conditional Statements

The structure of a switch / case condition is shown below:

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
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<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>
	<p>Nothing to show here.</p>
</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
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<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>
	<p>Nothing to show here.</p>
</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
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Simple Browser Sniffer</title>
<script type="text/javascript">
	switch (navigator.appName) {
		case "Microsoft Internet Explorer" :
			alert("This is IE!");
			break;
		case "Opera" :
			alert("This is Opera!");
			break;
		default :
			alert("This is something other than IE or Opera!");
	}
</script>
</head>
<body>
	<p>Your browser's <code>navigator.appName</code> is:
		<script type="text/javascript">
			document.write(navigator.appName);
		</script>.
	</p>
</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, Firefox, Chrome).

In conditional statements it's generally a good practice to test for the most likely cases/matches first so the browser can find the correct code to execute more quickly.

Next