What Is an If Statement?
An if statement tells JavaScript to run a block of code only when a condition is true. It is the most fundamental decision-making tool in the language.
let temperature = 30;
if (temperature > 25) {
console.log("It's hot outside!");
}
If the condition evaluates to false, the entire block is skipped and execution continues after the closing brace.
if / else
Add an else block to handle the case when the condition is false.
let age = 16;
if (age >= 18) {
console.log("You can vote.");
} else {
console.log("You are too young to vote.");
}
else if Chain
Chain multiple conditions with else if. JavaScript evaluates each condition from top to bottom and runs the first matching block.
let score = 75;
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");
}
Always put the most specific (narrowest) condition first. If you put score >= 60 at the top, everyone with a score β₯ 60 would get a "D" β the rest would never be reached.
Comparison Operators in Conditions
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Loose equal | 5 == "5" | true |
=== | Strict equal | 5 === "5" | false |
!= | Loose not equal | 5 != "6" | true |
!== | Strict not equal | 5 !== "5" | true |
> | Greater than | 10 > 5 | true |
< | Less than | 3 < 7 | true |
>= | Greater or equal | 5 >= 5 | true |
<= | Less or equal | 4 <= 3 | false |
Loose equality (==) performs type coercion and can produce surprising results like 0 == false being true. Prefer strict equality (===) in nearly every situation.
Truthy and Falsy Values
Every JavaScript value is either truthy or falsy when used in a boolean context. There are only six falsy values:
// The six falsy values
if (false) { /* never runs */ }
if (0) { /* never runs */ }
if (-0) { /* never runs */ }
if ("") { /* never runs */ }
if (null) { /* never runs */ }
if (undefined) { /* never runs */ }
if (NaN) { /* never runs */ }
// Everything else is truthy
if ("hello") { console.log("truthy string"); }
if (1) { console.log("truthy number"); }
if ([]) { console.log("empty array is truthy!"); }
if ({}) { console.log("empty object is truthy!"); }
This surprises many beginners. [] and {} are objects, and all objects are truthy. To check if an array is empty, compare arr.length === 0 instead.
Logical Operators in Conditions
Combine conditions using && (AND), || (OR), and ! (NOT).
let isLoggedIn = true;
let isAdmin = false;
let username = "Alice";
// AND β both must be true
if (isLoggedIn && isAdmin) {
console.log("Welcome, admin!");
}
// OR β at least one must be true
if (isLoggedIn || isAdmin) {
console.log("Access granted.");
}
// NOT β inverts the boolean
if (!isAdmin) {
console.log("You are not an admin.");
}
// Combining operators with parentheses
if (isLoggedIn && (isAdmin || username === "Alice")) {
console.log("Special access for Alice.");
}
Short-Circuit Evaluation
JavaScript stops evaluating a condition as soon as the result is known:
&&stops at the first falsy value and returns it||stops at the first truthy value and returns it
// || used for default values
let userName = "";
let displayName = userName || "Guest";
console.log(displayName); // "Guest"
// && used to safely access properties
let user = null;
let city = user && user.address && user.address.city;
console.log(city); // null (short-circuited, no error)
// Practical: default parameter before ES6
function greet(name) {
name = name || "Stranger";
console.log("Hello, " + name + "!");
}
greet(); // Hello, Stranger!
greet("Bob"); // Hello, Bob!
Ternary Operator (?:)
The ternary operator is a compact one-liner for simple if/else logic: condition ? valueIfTrue : valueIfFalse.
let age = 20;
// Traditional if/else
let status;
if (age >= 18) {
status = "adult";
} else {
status = "minor";
}
// Equivalent ternary
let status2 = age >= 18 ? "adult" : "minor";
console.log(status2); // adult
// Inline in template literals
console.log(`You are a${age >= 18 ? "n adult" : " minor"}.`);
// Ternary for JSX / HTML generation
let role = "editor";
let badge = role === "admin" ? "π‘οΈ Admin" : role === "editor" ? "βοΈ Editor" : "π€ User";
console.log(badge); // βοΈ Editor
Nested ternaries like a ? b : c ? d : e become hard to read. If you need more than one level, use an if/else chain instead.
Nested If β A Quick Look
You can place an if statement inside another if block. Keep nesting shallow to preserve readability.
let isLoggedIn = true;
let hasPremium = true;
if (isLoggedIn) {
if (hasPremium) {
console.log("Watch premium content.");
} else {
console.log("Upgrade to premium.");
}
} else {
console.log("Please log in.");
}
Real-World Examples
Age Category Checker
function getAgeCategory(age) {
if (age < 0) return "Invalid age";
if (age < 13) return "Child";
if (age < 18) return "Teenager";
if (age < 65) return "Adult";
return "Senior";
}
console.log(getAgeCategory(10)); // Child
console.log(getAgeCategory(16)); // Teenager
console.log(getAgeCategory(30)); // Adult
console.log(getAgeCategory(70)); // Senior
Login Validation
function login(username, password) {
if (!username || !password) {
return "Error: Username and password are required.";
}
if (username === "admin" && password === "secret") {
return "Welcome, admin!";
}
return "Invalid credentials.";
}
console.log(login("", "secret")); // Error: Username and password are required.
console.log(login("admin", "secret")); // Welcome, admin!
console.log(login("user", "wrong")); // Invalid credentials.
ποΈ Practical Exercise
Write a function getTicketPrice(age, isStudent) that returns a ticket price:
- Under 5: Free (0)
- 5β17 or student: $8
- 18β64: $15
- 65 and above: $10
Test with: getTicketPrice(3, false), getTicketPrice(20, true), getTicketPrice(25, false), getTicketPrice(70, false).
π₯ Challenge Exercise
Build a fizzBuzz(n) function using if/else if/else that:
- Returns "FizzBuzz" if n is divisible by both 3 and 5
- Returns "Fizz" if divisible by 3
- Returns "Buzz" if divisible by 5
- Returns the number as a string otherwise
Then call it for numbers 1 through 20 in a loop. Use the ternary operator to rewrite it in one expression.
π Summary
if (condition) {}runs code only when condition is truthy.else ifchains let you test multiple conditions in order.- Six falsy values:
false,0,"",null,undefined,NaN. - Always use
===(strict equality) instead of==. - Short-circuit:
||returns first truthy;&&returns first falsy. - Ternary
condition ? a : bis concise for simple if/else β avoid nesting it.
Interview Questions
- What is the difference between
==and===in JavaScript? - List all falsy values in JavaScript. What is surprising about empty arrays?
- Explain short-circuit evaluation. How is it used as a default-value pattern?
- When would you choose a ternary operator over an if/else statement?
- What is the difference between
&&and||returning a value vs. a boolean?
Frequently Asked Questions
Yes, you can omit braces when there is only one statement: if (x > 0) console.log("positive");. However, this is error-prone when you later add a second line and forget the braces. Most style guides require braces always.
Both handle conditional branching. Use switch when comparing one variable against many discrete values. Use if/else for range checks (age > 18) or complex boolean expressions.
No, there is no meaningful performance difference. Choose based on readability. Simple value assignments are fine as ternary; complex logic belongs in if/else blocks.
if ([]) {} run the block?+Because an empty array [] is an object, and all objects are truthy in JavaScript. To test if an array is empty, use if (arr.length === 0).