if, else, else if
if Statement
Use if to specify a code block to be executed, if a specified condition is true.
Syntax
if (condition) {
// code to execute if the condition is true
}
<!DOCTYPE html>
<html>
<body>
<h2>If Statement</h2>
<script>
let age = 20;
if (age >= 18) {
document.write("You can vote");
}
</script>
</body>
</html>
else Statement
Use else to specify a code block to be executed, if the same condition is false.
Syntax
if (condition) {
// code to execute if the condition is true
} else {
// code to execute if the condition is false
}
<!DOCTYPE html>
<html>
<body>
<h2>If Else Statement</h2>
<script>
let age = 16;
if (age >= 18) {
document.write("You can vote");
} else {
document.write("You cannot vote");
}
</script>
</body>
</html>
else if Statement
Use else if to specify a new condition to test, if the first condition is false.
Syntax
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if the condition1 is false and condition2 is true
} else {
// code to execute if the condition1 is false and condition2 is false
}
<!DOCTYPE html>
<html>
<body>
<h2>Else If Statement</h2>
<script>
let marks = 75;
if (marks >= 90) {
document.write("Grade A");
} else if (marks >= 70) {
document.write("Grade B");
} else {
document.write("Grade C");
}
</script>
</body>
</html>