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
In JavaScript, the if...else statement allows you to execute certain blocks of code based on a condition. If the condition evaluates to true, the code inside the if block will execute. If the condition evaluates to false, the code inside the else block will execute (if present).
In JavaScript, the if...else
statement allows you to execute certain blocks of code based on a condition. If the condition evaluates to true
, the code inside the if
block will execute. If the condition evaluates to false
, the code inside the else
block will execute (if present).
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
, theelse
block runs and displays"You are not eligible to vote."
You are eligible to vote.
Example with else if:
You can also nest multiple if...else
statements or use else if
for multiple conditions.
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.