JavaScript Tutorial
Master the fundamental building block of conditional logic in JavaScript. Learn how to make decisions in your code with if statements.
Why this matters
if statements are the foundation of decision-making in programming. Without them, your code would execute the same way every time, regardless of input or conditions.
What is an if Statement?
The if statement is the most basic form of conditional control flow in JavaScript. It allows you to execute a block of code only if a specified condition evaluates to true.
This is fundamental to programming as it enables decision-making based on different conditions or states in your application.
Basic if Statement
let age = 18;
if (age >= 18) {
console.log("You are eligible to vote!");
}
This code checks if age is 18 or older, and only prints the message if the condition is true.
if Statement Syntax
The syntax is simple: the keyword 'if' followed by parentheses containing the condition, then curly braces containing the code to execute.
The condition can be any expression that evaluates to true or false (truthy or falsy values).
if Statement Structure
if (condition) {
// code to execute if condition is true
}
The basic structure of an if statement. The code block only runs when the condition is truthy.
Multiple Conditions
let temperature = 25;
let isRaining = false;
if (temperature > 20 && !isRaining) {
console.log("Perfect weather for a walk!");
}
You can combine multiple conditions using logical operators like && (AND) and || (OR).
Truthy and Falsy Values
JavaScript has specific rules about which values are considered true or false in conditional statements.
Understanding these is crucial for writing correct if statements.
Truthy Values
// These are all considered true:
if (true) { console.log("true"); }
if (1) { console.log("1"); }
if ("hello") { console.log("hello"); }
if ([]) { console.log("array"); }
if ({}) { console.log("object"); }
All non-zero numbers, non-empty strings, arrays, and objects are truthy.
Falsy Values
// These are considered false:
if (false) { console.log("false"); } // false
if (0) { console.log("0"); } // 0
if ("") { console.log("empty"); } // empty string
if (null) { console.log("null"); } // null
if (undefined) { console.log("undefined"); } // undefined
if (NaN) { console.log("NaN"); } // NaN
Only these specific values are falsy. Everything else is truthy.
Common Use Cases
if statements are used in many real-world scenarios to make decisions based on data or user input.
User Authentication
let isLoggedIn = checkUserLogin();
if (isLoggedIn) {
showDashboard();
loadUserData();
} else {
showLoginForm();
}
Check if user is logged in before showing protected content.
Form Validation
function validateEmail(email) {
if (email.includes("@") && email.includes(".")) {
return true;
}
return false;
}
let userEmail = "user@example.com";
if (validateEmail(userEmail)) {
submitForm();
} else {
showError("Invalid email address");
}
Validate user input before processing forms.
Error Handling
let result = performCalculation();
if (result !== null) {
displayResult(result);
} else {
showError("Calculation failed");
}
Check for errors or null values before proceeding.
Best Practices
Writing clean, readable if statements makes your code more maintainable and less prone to bugs.
- Use descriptive variable names that make the condition self-explanatory
- Keep conditions simple - break complex conditions into multiple statements
- Use early returns to avoid deep nesting
- Add comments for complex business logic
- Consider using guard clauses for error conditions
Good Practice - Early Return
function processUser(user) {
if (!user) {
console.log("No user provided");
return;
}
if (!user.isActive) {
console.log("User is not active");
return;
}
// Process active user
console.log("Processing user:", user.name);
}
Handle error conditions early to avoid deep nesting and improve readability.
Common Mistakes
- Using = instead of ==: Use == or === for comparison, not = (assignment operator).
- Confusing truthy/falsy values: Explicitly check for the values you expect rather than relying on truthy/falsy behavior.
- Deep nesting of if statements: Use early returns or consider switch statements for multiple conditions.
Frequently Asked Questions
What's the difference between == and === in if statements?
== performs type coercion (converts types), === checks both value and type strictly.
Can I use if without curly braces?
Yes, but it's not recommended. Always use curly braces for clarity and to avoid bugs.
What happens if I don't provide an else clause?
The code simply continues executing normally if the condition is false.
Related Topics