JavaScript If Else
What is Control Flow?
JavaScript Control Flow refers to the way in which the execution of code progresses through a script. Control flow determines the order in which statements are executed, depending on conditions, loops, or other constructs.
JavaScript If Else
The if...else statement in JavaScript controls code execution based on a specified condition. If the condition holds true, the code inside the if block runs. When the condition is false the else block (if defined) runs its statements.
Syntax:
if (condition) {
// Code to run if the condition is true
} else {
// Code to run if the condition is false
}
Example:
if (condition) {
// Code to run if the condition is true
} else {
// Code to run if the condition is false
}
Here’s a simple example:
let age = 18;
if (age >= 18) {
console.log("You are eligible to vote.");
} else {
console.log("You are not eligible to vote.");
}
Explanation:
- The variable
age is set to 18.
-
The
if statement checks whether the condition age >= 18 is true.
- If
true, the message "You are eligible to vote." is displayed.
- If
false, the else block runs and displays "You are not eligible to vote."
Output:
age is set to 18.if statement checks whether the condition age >= 18 is true.
- If
true, the message"You are eligible to vote."is displayed. - If
false, theelseblock runs and displays"You are not eligible to vote."
You are eligible to vote.
Example with else if:
Multiple conditions can be handled using else if or nested if...else statements.
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");
}
Explanation:
- If the score is
90 or higher, the output will be "Grade: A".
- If the score is between
80 and 89, the output will be "Grade: B".
- If the score is between
70 and 79, the output will be "Grade: C".
- For any other score, the output will be
"Grade: F".
90 or higher, the output will be "Grade: A".80 and 89, the output will be "Grade: B".70 and 79, the output will be "Grade: C"."Grade: F".This flexibility allows you to handle a variety of conditions in your program.
Prefer Learning by Watching?
Watch these YouTube tutorials to understand Javascript Tutorial visually:
What You'll Learn:
- 📌 Conditional Statements If Else in JavaScript
- 📌 If statements in JavaScript are easy