What is a Conditional Statement?
A conditional statement is a syntax that controls the flow of execution in a program based on whether a certain condition is true or false
.
Much like "If it rains, use an umbrella, otherwise, don't," you can make the code execute different tasks based on specific conditions.
Necessity of Conditional Statements
Programs operate based on data and conditions related to that data.
Conditional statements are essential elements when designing a program to operate differently depending on the state of the data.
For example, you can use a conditional statement to show different messages based on user input, or to end a game when a character's health reaches zero.
if Statement
The if statement executes a block of code if the condition is true.
if (condition) {
// Code to be executed if the condition is true
}
What is a Condition?
A condition is an expression that evaluates to either true or false.
For example, the expression x > 10
is true if the value of x is greater than 10, and false otherwise.
Example
let age = 21;
if (age >= 20) {
console.log('You are an adult');
}
// Output: You are an adult
else Statement
The else statement defines a block of code that will be executed if the condition is false.
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Handling Multiple Conditions with else-if Statement
You can handle multiple conditions using the else if statement.
When using if, else if, and else together, only the block of code corresponding to the first true condition will be executed.
let score = 85;
if (score >= 90) {
console.log('Grade A');
} else if (score >= 80) {
console.log('Grade B');
} else {
console.log('Grade C');
}
// Output: Grade B
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.