Single-Branch Decisions
The if statement runs a block only when a condition is true.
Use it for guard clauses, validation, and early returns.
JavaScript Tutorial
The if statement is the simplest way to execute code conditionally in JavaScript.
It runs a block only when a condition evaluates to true.
Most application logic starts with simple checks like if a user is logged in or if data is valid.
Clear if statements make control flow easy to understand and maintain.
if (condition) { ... }const isOnline = true;
if (isOnline) {
console.log("User is online");
}The block runs only when the condition is true.
function submit(form) {
if (!form.isValid) return;
console.log("Submitting...");
}Guard clauses exit early when a condition fails.
The if statement runs a block only when a condition is true.
Use it for guard clauses, validation, and early returns.
Any expression that evaluates to true or false can be used in an if condition.
Prefer explicit comparisons for clarity.
Keep if conditions short. Extract complex logic into named variables.
This makes code easier to scan and review.
Without
let label = "";
if (isActive) {
label = "Active";
}With
const label = isActive ? "Active" : "";Extract logic into named booleans for readability.
Use === for comparisons, not =.
Use explicit comparisons when values can be 0 or empty strings.
Use guard clauses or return early to keep nesting shallow.
It runs a block only when a condition is true.
They reduce nesting and make code easier to read.
Any value that coerces to true in a boolean context.
Practice: Check if a cart total is above a free-shipping threshold and log a message.
const total = 65;
// TODO: log "Free shipping" only if total >= 50
One Possible Solution
const total = 65;
if (total >= 50) {
console.log("Free shipping");
}Yes, but it will be coerced to a boolean. Explicit comparisons are clearer.
An early return that exits when a condition fails.
Performance differences are usually negligible. Choose for readability.
Try changing the condition to see when the if block executes.