Book
Submodule 6.2: Making Decisions
Submodule 6.2: Making Decisions
Completion requirements
View
- Comparison operators
- If statements
- Logical operators
The else if statement
The else if statement is another condition. This is used when we want to do more than one tests.
As you may expect, the else if statement is always after an if statement.
You can use as many else if statements as you need.
if (expression){
//this code runs if expression evaluates to true
}else if (expression2){
//this code runs if expression2 evaluates to true
}else{
//this code runs if neither are true
}
Example
In this example, we say: "If our number is smaller than 5 do something, else if it is equal to 5 do something else. Else, if neither of the above is true, go and do something else.
<!DOCTYPE html>
<html lang="en">
<head>
<title>The if else if statement </title>
</head>
<body>
<h3> The if else if statement</h3>
<script>
var a = 5;
var myNum;
myNum = prompt("Write a number?");
if (myNum < a) {
document.write("You wrote the number " + myNum + ". This number is less than " + a +".")
} else if (myNum == a) {
document.write("You wrote the number " + myNum + ". This number is equal to " + a +".")
} else {
document.write("You wrote the number " + myNum + ". This number is greater than " + a +".")
}
</script>
</body>
</html>
Exercise
- Open your editor, create a new file and save it as
exersice06.2.04ifelseif.html
in the folder "yourNameWEB2JS". - Copy the above code and paste it into the new file.
- Save the file and preview it in your editor or your browser.
- Check your code by inserting the numbers 4,5,6 in the prompt window. What do you see?
Here, all the cases work correctly! Experiment by changing the variable a