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
ifStatement
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-elseStatement
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-elseStatement
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
ifStatements
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
ifstatement allows you to control the flow of your program based on conditions. - The
if-elsestatement provides an alternative path when the condition is false. - The
if-else if-elsestatement allows for multiple conditions to be checked in sequence. - Nested
ifstatements 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.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
