What is a Conditional Statement?
A conditional statement is a syntax structure used to control the flow of a program based on whether a specific condition is true or false
.
Much like saying "if it rains, take an umbrella; otherwise, don't," you can also make your code execute different actions depending on certain conditions.
Importance of Conditional Statements
Programs operate based on data and conditions applied to that data.
Conditional statements are essential for designing programs to behave differently depending on the state of the data.
For example, you might use a conditional statement to display 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 execute 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
becomes 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 to be executed if the condition is false.
if (condition) { // Code to execute if the condition is true } else { // Code to execute if the condition is false }
Handling Multiple Conditions with else-if
You can handle multiple conditions using the else if statement.
By 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
Why do we use else if statements in conditionals?
To execute a code block when the condition is true
To define a code block to be executed when the condition is false
To handle multiple conditions and execute only the code block of the first true condition
To ensure code executes without any conditions
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result