The if-else statement in JavaScript is a fundamental control structure used to execute different blocks of code based on whether a condition evaluates to true or false. It allows for decision-making in your code, enabling you to run specific code only when certain conditions are met. This is essential for creating dynamic and responsive web applications.
There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement
Introduction: The if statement is the simplest form of decision-making in JavaScript. It evaluates a condition and executes a block of code if the condition is true. If the condition is false, the code block is skipped.
Use: Use the if statement when you need to execute a block of code only when a specific condition is met and there is no need to handle the false case
<script>
var age = 18;
if (age >= 18) {
console.log("You are an adult.");
}
</script>
Introduction: The if-else statement extends the if statement by adding an alternative block of code to execute if the condition is false. This allows you to handle both outcomes: when the condition is true and when it is false.
Use: Use the if-else statement when you need to execute one block of code if a condition is true and a different block if the condition is false.
<script>
var age = 16;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
</script>
Introduction: The if-else if-else statement allows for multiple conditions to be checked in sequence. If the initial if condition is false, the else if conditions are evaluated in order. If none of the conditions are true, the else block is executed.
use: Use the if-else if-else statement when you need to handle multiple possible conditions and execute different code blocks based on which condition is met.
<script>
var score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: D");
}
</script>