JavaScript If Statements
The If statement as we all know tests a condition and then according to the result, like it is true
or false
, a particular block of code
is performed. Same as that, the JavaScript if statement is used to execute a specific block of code with the given conditions. Only if the condition evaluates to true then the defined block of code is executed otherwise not.
There are three forms of if statement in JavaScript.
- If Statement
- If Else Statement
- If Else if Statement
JavaScript If Statement
The if
statement tests a specified condition and then if the condition evaluates to true then the block of code defined in the if
statement gets executed otherwise the block is skipped.
Syntax:
if (condition)
{
//code to be executed if condition is true;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript If Statement </title>
</head>
<body>
<script>
var x = 100;
if(x > 10){
document.write("Value of x is greater than 10");
}
</script>
</body>
</html>
Output
JavaScript If Else Statement
In the previous statement there was no block of code defined for the false evaluation of the condition, which is defined here in else
statement. The if....else
statement also tests a condition but here the else
statement is present. The if
block's code gets executed if the given condition is true otherwise if the condition is false then the else
block's code gets executed.
Syntax:
if (condition)
{
//code to be executed if condition is true;
}
else {
//code to be executed if condition is false;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript If Else Statement </title>
</head>
<body>
<script>
var a=20;
if(a%2==0){
document.write("Even number");
}
else{
document.write("Odd number");
}
</script>
</body>
</html>
Output
JavaScript If Else Statement Examples
JavaScript If... Elseif Statement
JavaScript if...elseif
statement tests multiple conditions and executes different blocks of code for more than two conditions
. First, a condition specified in if
statement is tested, then if that evaluates to false, then only the elseif
's statement is tested. And if else
statement is defined and both the previous condition evaluates to false then only the else
statement gets executed.
Syntax:
if (condition)
{
//code to be executed if condition is true;
}
elseif (condition) {
//code to be executed if condition is true;
}
else {
//code to be executed if all conditions are false;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript If Else If Statement </title>
</head>
<body>
<script>
var a=15;
if(a==10){
document.write("Number is equal to 10");
}
else if(a==15){
document.write("Number is equal to 15");
}
else if(a==20){
document.write("Number is equal to 20");
}
else{
document.write("Number is not equal to 10, 15 or 20");
}
</script>
</body>
</html>
Output
JavaScript If Else If Statement