Learn how to build and design websites with our tutorials.

JavaScript Conditional Statements Tutorial

View Tutorial Contents


Introduction To Conditional Statements

Javascript statements are executed in the order in which they appear in a script or program, which is one after another. This of course is not practical. Luckily, Javascript, like other programming languages let you control in which order your code is executed. This is called flow control. This is done with the use of conditional statements.

The types of conditional statements are listed below.

Functions are covered in our functions tutorial. This tutorial will go over the other conditional statements.


if Statements

Javascript if statements state that if a specified condition is true, to execute the code that follows.

The syntax for an if statement is shown below.


if(condition){
 // execute this code if the condition is true
};

A Javascript if statement begins with the Javascript if keyword, immediately followed by a set of parenthesis (()). A set of curly brackets ({})follow the parenthesis. The parenthesis contain the condition. If the condition is true, the code within the curly brackets will be executed.

The HTML and Javascript code below contains an example of an if statement.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>


<script>

var number = 1;
if(number === 1){
	alert("The condition is true.");
};

</script>
</body>
</html>

The HTML and Javascript code above will output an alert box with the text "The condition is true.", because the condition is true.

In the example above, the Javascript equal value and type comparison operator (===) is used to check whether the condition evaluates to true or not true.

In this example, the condition is true, so the code within the curly brackets that follow is executed.

Since there is only one line of code to be executed (a statement) you do not need to include the curly braces and can place this entire if statement on one line, however, this is not a recommended practice. It is best to always include the curly braces and to write your if statements in a way that is easier to read, like the example shown above.

You can also write the condition to be evaluated above as shown below.


var number = 1;
if(number){
	alert("The condition is true.");
};

You can also have as many statements that you want to be executed within an if statement. You can one statement, or you could have 100 or more statements if you wanted to, though that would not be practical.


Conditional Operators and if Statements

The condition part of an if statement is called a conditional expression. A conditional expression usually has two or more values that are to be compared. These values can be variables, constants or even other expressions.

Between any two values that are to be compared is a conditional operator. The conditional operator that is between any two values tells Javascript how to compare them.

In the example below, the condition operator is used to check whether the variable "number" is equal in value and type as 1.


var number = 1;
if(number === 1){
	alert("The condition is true.");
};

The table below lists the Javascript comparison operators.

Operator Description
== equal to
=== equal value and type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to

Combining Conditions and Logical Operators

Javascript lets you check a variable for more than one possible value, and/or to check more than one variable at once with the use of logical operators, also called boolean operators.

The table below lists the JavaScript logical operators and a description of each.

Operator Description
&& and
|| or
! not

In the example below, an if statement check whether someone is older than at least 18 years old or older and another if statement checks whether the same person is 21 years old or younger.

In the example below, I introduce the else statement. I will go over the else statement a little later in this tutorial.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>


<script>

var Jane = 19;
if(Jane >= 18){
	alert("Yes, Jane is at least 18 years old.");
}
else{
	alert("Jane is too young.");
}


if(Jane <= 21){
	alert("Jane is not older than 21.");
}
else{
	alert("Jane is too old.");
}

</script>
</body>
</html>

Using the logical AND operator (&&), you can combine both if statements into one if statement as shown below.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>


<script>

var Jane = 19;
if(Jane >= 18 && Jane <= 21){
	alert("Yes, Jane is between at least 18 years old and not older than 21 years old.");
}
else{
	alert("Jane is either too young or too old.");
}

</script>
</body>
</html>

In the example above, the logical && operator allows you to combine both statements into one if statement.

The logical OR operator (||) returns true if one or both expressions are true, otherwise it returns false.

In the example below, the logical OR operator allows you check whether x is equal in value and type to 'a' or 'A' in one single if statement.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>


<script>

var x = 'A';
if(x === 'a' || x === 'A'){
	alert("The answer is letter A.")
}else{
	alert("The answer is not letter A.");
}

</script>
</body>
</html>

The Javascript logical NOT operator (!) returns true for false statements and false for true statements.

In the example below, the NOT operator is used to check if the variable "name" IS NOT equal in value and type to "Bill". If it is not, it returns true.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>


<script>

var name = "John";
if(!(name === "Bill")){
	alert("This is not Bill.");
}
else{
	alert("This is Bill.");
}

</script>
</body>
</html>

The example above will alert "This is not Bill." because the variable "name" IS NOT equal in value or type to "Bill".


else Statements

Javascript else statements specify a statement or block of code that should be executed if the condition in the if statement is false.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>


<script>

var number = 100;
if(number === 1){
	alert("The condition is true.");
}
else{
	alert("The condition is false.");
}

</script>
</body>
</html>

In the example above, the condition is false so the statement within the else statement will be executed. It will alert the message "The condition is false.".


else if Statements

Javascript allows you to check multiple conditions with the use of else if statements. An else if statement specifies a condition that is to be evaluated if the previous condition failed. You can add as many else if statements as you want.

In the example below, multiple conditions are checked using else if statements. If none of the conditions are true, the code in the else statement is executed.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>


<script>

var grade = "D";
if(grade === "A"){
	alert("You got an A");
}
else if(grade === "B"){
	alert("You got a B");
}
else if(grade === "C"){
	alert("You got a C");
}
else if(grade === "D"){
	alert("You got a D");
}
else{
	alert("You got an F");
}

</script>
</body>
</html>

In the example above, multiple conditions are checked and the third condition evaluates to true and the text "You got a D" is displayed in an alert message.


switch Statements

The Javascript switch statement is an alternative to else if statements. The switch statement allows you to combine several tests of the same variable or expression into a single block of statements. else is statements are typically used when there are only a few conditions to test for. switch statements are typically used when there are more than a few conditions to evaluate for.

The syntax for a switch statement is shown below.


switch (expression){
	case value#1:
		// code to be executed
		break;
	case value#2:
		// code to be executed
		break;
	case value#3:
		// code to be executed
		break;
	default:
		// code to be executed
};

In the example below, the switch statement tests for the variable "grade" to be true. In the first case, if the variable evaluates to "a", which would mean that it evaluated to true, the code for that case would be executed. The break keyword tells Javascript to stop testing other cases and to not execute any other code within the switch statement. If the first case does not evaluate to "a", Javascript moves on and tests for the next case. It does this until a case evaluates to true, or if none of the cases evaluate to true, it executes the code that appears after the default keyword.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>


<script>

var grade = "d";
switch(grade){
	case "a":
		alert("The letter is a.");
		break;
	case "b":
		alert("The letter is b.");
		break;
	case "c":
		alert("The letter is c.");
		break;
	case "d":
		alert("The letter is d.");
		break;
	case "e":
		alert("The letter is e.");
		break;
	default:
		alert("None of the above");
};

</script>
</body>
</html>

The example above will alert the text "The letter is d.".


Condition (Ternary) Expression

Javascript also offers a shorthand type of if else statement called a condition ternary expression. A conditional ternary expression assigns one of two values to a variable based on whether an expression is true or false.

The syntax for an conditional ternary expression is shown below.


var variableName = (condition) ? value #1 : value #2;

Below is an example of a conditional ternary expression.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>


<script>

var login = "logged in";
var status = (login) ? "Logged in" : "Not logged in";
alert(status);

</script>
</body>
</html>

The example above will alert "Logged in".


for Loops

Javascript for loops allow you to go through a same block of code over repeatedly (also called to iterate). for loops are often used when you need to iterate over arrays.

The best way to explain a for loop is to go over a simple example, as shown below.


for (i = 0; i < 10; i++){
    // code block to be executed
}

The keyword for initiates the for loop, followed by parenthesis which contain three expressions, followed by the code that is to be executed each time that the code is iterated over.

The first expression within the parenthesis, "i = 0;", in this example, declares a variable which acts as the starting point.

The second expression states up to what number the for loop should iterate to.

The third expression states the number by which the loop should increment each time that the for loop iterates over the code.

In the example below, a for loop is used to iterate over an array. The result is placed in a variable which is output to a paragraph.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>

<p id="demo">
</p>

<script>

var cars = ["Toyota", "Honda", "Ford", "Chevrolet"];
var text = "";
var i;
for (i = 0; i < cars.length; i++){
    text += cars[i] + "<br />";
};

document.getElementById("demo").innerHTML = text;

</script>
</body>
</html>

The example above will output the paragraph below.

Toyota
Honda
Ford
Chevrolet

In the example above, there is an array called cars. That array is iterated over using a for loop. To begin the, a variable is set before the for loop starts (i = 0;). Next, the condition for the for loop is set (i < cars.length). The length property is used to get the number of items that are in the array. Next, the value of the variable i is incremented each that the for loop is iterated over.

The results of the for loop is placed in a variable called text. The variable text is then output into a paragraph with the id of demo once the for loop has been iterated over.

The letter i was used as the variable name, but any acceptable variable name can be used.

The array was incremented using the increment operator (++).


while Loops

Javascript while loops loop through and execute a block of code as long as a specified condition is true. If the condition starts out as false, Javascript will not loop through and execute the block of code.

The syntax for a while loop is shown below.


while(condition){
	// code block to be executed
};

A while loop begins with the while keyword, followed by a set of parenthesis (()) which contain the condition that should evaluate to either true or false. After the parenthesis follows a set of curly braces ({}). The curly braces contain the block of statements that should be executed as they are looped through.

In the example below, a while loop will iterate through the block of code as long as the variable (i) in the example is less than 10.

You must increase the variable count within block of code or else the loop never end and will cause the web browser to crash. In the example below, the variable along with the increment operator (i++) are used to increase the variable count.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>

<button onclick="myFunction()">Click Here</button>

<p id="demo"></p>

<script>

function myFunction(){
	var text = "";
	var i = 0;
	while (i < 10){
		text += "<br />The number is " + i + ".";
		i++;
	};
	document.getElementById("demo").innerHTML = text;
};

</script>
</body>
</html>

The example above will output the button and the paragraph below.


do while Loops

The Javascript do/while loop is like the while loop, except that Javascript will execute the block of code at least once before checking if the condition evaluates to true. If the condition is true, it will continue to execute the loop as long as the condition is true.

The syntax for a do/while loop is shown below.


do{
	// code block to be executed
}
while (condition);

A do/while loop begins with the do keyword followed by a set of curly braces ({}) which contain the block of code that is going to be executed, followed by the while keyword followed by a set of parenthesis (()) which contain the condition that should evaluate to true or false.

In the example below, the block of code within the do statement is executed once before evaluating that the condition is true and then continues to iterate over the block of code until the condition evaluates to false.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>

<button onclick="myFunction()">Click Here</button>

<p id="demo"></p>

<script>

function myFunction(){
	var text = ""
	var i = 0;
	do{
		text += "<br />The number is " + i;
		i++;
	}
	while(i < 10)
    document.getElementById("demo").innerHTML = text;
};

</script>
</body>
</html>

The example above will output the button and the paragraph below.


Javascript break Statement

Javascript provides you with the break statement and the continue statement so that you can have more control over your loops and switch statements. For example, you may want a loop or a switch statement to stop when you want skip over some iterations within your loops.

The Javascript break statement is used to exit (also called to break or jump out of) a loop.

The example below contains a for loop.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>

<p id="demo"></p>

<script>

var i;
var text = "";
for (i = 1; i <= 10; i++) {
    text += [i] + "<br />";
}
document.getElementById("demo").innerHTML = text;

</script>
</body>
</html>

The example above outputs the paragraph below.

1
2
3
4
5
6
7
8
9
10

The example below is the same as the example above, except that it contains a break statement.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>

<p id="demo"></p>

<script>

var i;
var text = "";
for (i = 1; i <= 10; i++) {
    text += [i] + "<br />";
    if(i === 5){
    	break;
    }
}
document.getElementById("demo").innerHTML = text;

</script>
</body>
</html>

The example above outputs the paragraph below.

1
2
3
4
5


Javascript continue Statement

The Javascript continue statement breaks one iteration within the loop if the condition that is specified occurs, it then continues with the next iteration in the loop.

The example below contains a continue statement. Notice that the if statement, which contains the continue statement, comes before the block of code that is to executed within the for statement.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>
</style>
</head>
<body>

<p id="demo"></p>

<script>

var i;
var text = "";
for (i = 1; i <= 10; i++) {
    if(i === 5){
    	continue;
    }
    text += [i] + "<br />";
}
document.getElementById("demo").innerHTML = text;

</script>
</body>
</html>

The example above outputs the paragraph below. Notice that the number five is not listed.

1
2
3
4
6
7
8
9
10