Conditional Statements
Making Decisions in Code
Programs aren't very useful if they just run from top to bottom every single time. Real applications need to make decisions: "If the user is logged in, show the dashboard; otherwise, show the login page."
We do this using conditional statements.
The if Statement
The if statement executes a block of code only if a specified condition evaluates to true.
let age = 18;
if (age >= 18) {
console.log("You are eligible to vote!");
}
Because 18 >= 18 is true, the console log will run.
The else Statement
What if the condition is false? You can use an else block to specify code that should run when the if condition fails.
let age = 16;
if (age >= 18) {
console.log("You are eligible to vote!");
} else {
console.log("You are too young to vote.");
}
Here, the condition is false, so it skips the if block and runs the else block instead.
Conditionals are the foundation of logic in programming. They allow your applications to react to user inputs and changing data dynamically!
💡 Himanshu's Tip:
Keep your if conditions simple. If you find yourself writing if (userIsLoggedIn === true && userAge >= 18 && hasPaid === true), extract that into a separate variable like let canAccessCourse = ... and just write if (canAccessCourse). It makes your code read like plain English!
Interview Questions
- What happens if the condition inside an
ifstatement evaluates to false? - Can you have an
ifstatement without anelseblock? - What data type must the condition inside the parentheses evaluate to?