The most often used flow control statement is if statement, or extended if...else if...else.

This kind of statement controls the flow of the code execution based on the results of given comparison, as shown here:

if (expression) {

   statament1;

}

else {

   statement2;

}

The expression is converted into a Boolean (true or false) value and comparison is executed.

If the expression above evaluates to true (i.e. 5 > 2), then the statement1 will get executed; otherwise statement2 gets executed.

The if...else statement may be expandeded into if...else if...else statement, as shown here:

if (expression) {

   statament1;

}

else if {

   statement2;

}

else {

   statement3;

}

The else if extension is not limited to only one else if but in case of needing more than a couple, it is advised to use switch statement instead, which is more suitable for multiple flow detours.

Example

The example with if statement in JavaScript:

x
 
<!DOCTYPE html>
<html>
<head>
<title>JS tutorial</title>
<style type="text/css">
body {
    margin-top:20px;
    background-color:#efe;
}
</style>
<script type="text/javascript">
function compare() { 
    var a = document.getElementById("a").value;
    var b = document.getElementById("b").value;
    var result = document.getElementById("result"); 
    if (a > b) {
        result.textContent = "result = "+ a + " is greater than " + b;
    }
    else if (a < b) {
        result.textContent = "result = "+ a + " is less than " + b; 
    }
    else if (a === b) {
        result.textContent = "result = values are identical";
    }
    else {
        result.textContent = "Oops! Not possible to compare.";
    }
}
</script>   
</head>
<body>
    <h5>Enter values into these boxes and test compare them:</h5>
    <form action="" method="post">
    <input type="text" id="a" maxlength="4" size="4" />&nbsp;&amp;&nbsp;<input type="text" id="b" maxlength="4" size="4" />
    <input type="button" id="subm" onclick="compare()" value="compare" />
    </form>
    <pre id="result">result = ?</pre>
</body>
</html>

 

›› go to examples ››