JavaScript Conditionals
Run different code based on conditions.
- Conditional statements help programs make decisions.
- They run different code when a condition is true or false.
- If it is raining, take an umbrella.
- If you are hungry, eat food.
- If the traffic light is green, move forward.
Why Are Conditional Statements Important?
- React to different values and situations.
- User login systems
- Form validation
- Age verification
- Online shopping discounts
- Access control and permissions
The if Statement
- if is the simplest conditional statement.
- Its code runs only when the condition is true.
JavaScript
let age = 20;
if (age >= 18) {
console.log("You are eligible to vote.");
}JavaScript
You are eligible to vote.- The if block runs because age is 18 or higher.
The if...else Statement
- if runs when the condition is true.
- else runs when the condition is false.
JavaScript
let age = 16;
if (age >= 18) {
console.log("You can vote.");
} else {
console.log("You cannot vote yet.");
}JavaScript
You cannot vote yet.- The else block runs because age is below 18.
The if...else if...else Statement
- Use else if to check multiple conditions.
- JavaScript runs the first matching block.
JavaScript
let score = 85;
if (score >= 90) {
console.log("Grade A");
} else if (score >= 75) {
console.log("Grade B");
} else if (score >= 60) {
console.log("Grade C");
} else {
console.log("Grade D");
}JavaScript
Grade B- The Grade B block is the first condition that matches.
The switch Statement
- Use switch to compare one value with multiple options.
- break stops execution after a matching case.
- default runs when no case matches.
JavaScript
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week");
break;
case "Friday":
console.log("Weekend is near");
break;
default:
console.log("Regular day");
}JavaScript
Start of the weekNested Conditional Statements
- A conditional can contain another conditional.
- This is called a nested conditional.
JavaScript
let isLoggedIn = true;
let isAdmin = true;
if (isLoggedIn) {
if (isAdmin) {
console.log("Welcome Admin");
}
}Key Takeaways
- Use if for one condition.
- Use if...else for two possible paths.
- Use else if for multiple conditions.
- Use switch when one value has several possible matches.
