Control Flow -if Statement
In JavaScript, control flow refers to the order in which the individual statements, instructions, or function calls of a program are executed or evaluated. The if statement is a fundamental part of control flow, allowing you to execute certain pieces of code based on whether a condition is true or false.
Basic Syntax of if Statement
if (condition) {
// code to be executed if the condition is true
}
Examples of if Statements
- Simple
if Statement
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
}
Output:
You are an adult.
In this example, the condition age >= 18 evaluates to true, so the code inside the if block is executed.
if-else Statement
let age = 16;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
Output:
You are a minor.
Here, since age >= 18 is false, the code inside the else block is executed.
if-else if-else Statement
let 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: F");
}
Output:
Grade: B
In this example, the first condition score >= 90 is false, but the second condition score >= 80 is true, so the corresponding block of code is executed.
- Nested
if Statements
let number = 10;
if (number > 0) {
console.log("The number is positive.");
if (number % 2 === 0) {
console.log("The number is even.");
} else {
console.log("The number is odd.");
}
} else {
console.log("The number is not positive.");
}
Output:
The number is positive.
The number is even.
Here, the first condition number > 0 is true, so the outer if block is executed. Within this block, there is another if statement to check if the number is even or odd.
Summary
- The
if statement allows you to control the flow of your program based on conditions.
- The
if-else statement provides an alternative path when the condition is false.
- The
if-else if-else statement allows for multiple conditions to be checked in sequence.
- Nested
if statements enable more complex decision-making structures.
Using these control flow structures, you can create programs that make decisions and respond to different inputs and conditions dynamically.