Topic 26 of 87
if / else
Overview
The if/else statement is the most fundamental control flow mechanism in JavaScript. It allows you to execute specific blocks of code based on whether a condition evaluates to true or false.
You can chain multiple conditions together using else if. JavaScript evaluates the conditions from top to bottom and executes the first block that evaluates to true, ignoring all subsequent blocks.
Syntax
Basic if/else Structure
javascript
const temperature = 30;
if (temperature > 35) {
console.log("It's dangerously hot!");
} else if (temperature > 25) {
// This block runs because 30 > 25
console.log("It's a nice warm day.");
} else {
// Catch-all if nothing above is true
console.log("It's a bit chilly.");
}Omitting Braces (Not Recommended)
javascript
// JS allows omitting braces for single-line statements
if (isValid) console.log("Valid");
else console.log("Invalid");Common Pitfalls
- Omitting curly braces
{}. While JavaScript allows you to omit braces for a single line of code after anif, it is a massive source of bugs. If another developer adds a second line later and forgets the braces, that second line will run unconditionally. - Assigning instead of comparing inside the condition:
if (x = 10). This assigns 10 toxand evaluates to true, causing a silent bug.
Interview Questions
Q:
What are 'truthy' and 'falsy' values in JavaScript
if statements?A:
JavaScript coerces conditions to booleans. The following 6 values are falsy: false, 0, "" (empty string), null, undefined, and NaN. Absolutely everything else (including empty arrays [] and empty objects {}) evaluates to true.
Real-World Example
Determining what UI to show a user based on their authentication status.
example
javascript
if (user.isLoggedIn) {
renderDashboard();
} else {
redirectToLogin();
}Check Your Knowledge
Test your understanding of if / else with these quick questions.