The if Statement
The if statement has the following syntax:
if (condition)
statement1
else
statement2
In the following code the conditional expression compares the value myAge against a numeric value of 13:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var myAge = 12;
if (myAge < 13)
{
document.writeln("under 13.");
}
</script>
</head>
<body>
</body>
</html>
The condition can be any expression.
JavaScript converts the result of the expression into a Boolean by calling the Boolean() casting function.
The following code output true:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var i = 3;
if (i){
document.writeln("true");
}
else {
document.writeln("false");
}
</script>
</head>
<body>
</body>
</html>
You can also chain if statements together like:
if (condition1)
statement1
else if (condition2)
statement2
else
statement3
Here's an example:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var i = 50;
if (i > 25) {
document.writeln("Greater than 25.");
} else if (i < 0) {
document.writeln("Less than 0.");
} else {
document.writeln("Between 0 and 25, inclusive.");
}
</script>
</head>
<body>
</body>
</html>