JavaScript if Statement
The if statement executes a block of code if a specified condition is true. It is the most fundamental control structure in JavaScript and the basis for all decision-making in your programs.
if Statement Syntax
The if statement evaluates a condition inside parentheses. If the condition is true, the code block inside the curly braces executes. If false, it is skipped.
let temperature = 35;
if (temperature > 30) {
console.log("It's hot outside!");
}
// Output: "It's hot outside!"
if (temperature > 40) {
console.log("Extreme heat!");
}
// No output (condition is false)if...else Statement
The else block executes when the if condition is false. This lets you handle both outcomes of a condition.
let age = 16;
if (age >= 18) {
console.log("You can vote");
} else {
console.log("You cannot vote yet");
}
// Output: "You cannot vote yet"
let number = 7;
if (number % 2 === 0) {
console.log(number + " is even");
} else {
console.log(number + " is odd");
}
// Output: "7 is odd"else if — Multiple Conditions
Use else if to test multiple conditions in sequence. JavaScript evaluates each condition top-down and executes only the first matching block.
let score = 72;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else if (score >= 60) {
console.log("Grade: D");
} else {
console.log("Grade: F");
}
// Output: "Grade: C"Nested if Statements
You can place if statements inside other if statements. However, deeply nested code is harder to read — consider using guard clauses or logical operators instead.
let age = 25;
let hasLicense = true;
if (age >= 18) {
if (hasLicense) {
console.log("You can drive");
} else {
console.log("Get a license first");
}
} else {
console.log("Too young to drive");
}
// Output: "You can drive"
// Better: use && to avoid nesting
if (age >= 18 && hasLicense) {
console.log("You can drive");
} else if (age >= 18) {
console.log("Get a license first");
} else {
console.log("Too young to drive");
}Multiple Conditions with && and ||
Use && (AND) to require multiple conditions to be true. Use || (OR) to require at least one condition to be true. Combine them for complex logic.
let age = 25;
let income = 50000;
let hasGoodCredit = true;
// AND: all conditions must be true
if (age >= 18 && income >= 30000 && hasGoodCredit) {
console.log("Loan approved");
}
// Output: "Loan approved"
// OR: at least one must be true
let day = "Saturday";
if (day === "Saturday" || day === "Sunday") {
console.log("It's the weekend!");
}
// Output: "It's the weekend!"
// Combining AND and OR (use parentheses!)
let role = "admin";
let isOwner = false;
if (role === "admin" || (role === "editor" && isOwner)) {
console.log("Full access granted");
}
// Output: "Full access granted"