/

HTML / CSS / JavaScript Tutorial

JavaScript Statement: if … else if … else

[this page | pdf | back links]

In JavaScript, the if statement marks a block of statements to be executed depending on a condition. There are three types of if statement:

 

(1)   if (…) {…}

(2)   if (…) {…} else {…}

(3)   if (…) {…} else if (…) {…}

 

The expression within the (first) normal brackets, i.e. within matching “(“ and “)”, should evaluate to a Boolean (i.e. be a condition).  If this condition is true then the next code block (within curly brackets) will be executed, whilst if this condition is false and there is an else statement then the code in the second curly brackets in (2) would be executed. The else if variant in (3) allows further (potentially several nested) conditions to be included and can include a final else block as per (2).

 

There is one further type of conditional statement, the switch statement, which is (typically) used when there are multiple cases each of which would trigger execution of different code blocks.

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>

<script>
var s = 3;
var x;
if (s==3) {x = 5;};
if (s==1) {x = x + 10;}
  else if (s==2) {x = x + 20;}
  else {x = x + 30;};
document.getElementById("Example").innerHTML =
  'var s = 3;<br>' +
  'var x;<br>' +
  'if (s==3) {x = 5;}<br>' +
  'if (s==1) {x = x + 10;}<br>' +
  '&nbsp;&nbsp;elseif (s==2) {x = x + 20;}<br>' +
  '&nbsp;&nbsp;else {x = x + 30;};';
document.getElementById("Result").innerHTML = x;
</script>

</body>
</html>


NAVIGATION LINKS
Contents | Prev | Next | JavaScript Reserved Words


Desktop view | Switch to Mobile