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:
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 to18
. -
The
if
statement checks whether the conditionage >= 18
istrue
.- If
true
, the message"You are eligible to vote."
is displayed. - If
false
, theelse
block runs and displays"You are not eligible to vote."
- If
Output:
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
and89
, the output will be"Grade: B"
. - If the score is between
70
and79
, the output will be"Grade: C"
. - For any other score, the output will be
"Grade: F"
.
This flexibility allows you to handle a variety of conditions in your program.