JavaScript Notes
Learn the JavaScript if statement with syntax, truthy/falsy values, logical operators, flowcharts, real-world programs, common mistakes, and 12 interview Q&As for beginners.
The if statement is the most fundamental control flow structure in JavaScript. It allows you to execute a block of code only when a specified condition evaluates to true. Understanding if statements is essential for making decisions in your programs.
What is an If Statement?
An if statement evaluates a condition (an expression that returns a boolean value) and executes the associated code block only if that condition is true. If the condition is false, the code block is skipped entirely.
Syntax
if (condition) {
// code to execute if condition is true
}The parentheses () around the condition are required. The curly braces {} define the code block to execute.
Basic Examples
Example 1: Simple Condition Check
let age = 18;
if (age >= 18) {
console.log("You are eligible to vote!");
}
console.log("Program continues...");You are eligible to vote! Program continues...
Example 2: Condition is False
let temperature = 25;
if (temperature > 30) {
console.log("It's a hot day!");
}
console.log("Temperature check complete.");Temperature check complete.
Since 25 > 30 is false, the if block is skipped.
Example 3: String Comparison
let username = "admin";
if (username === "admin") {
console.log("Welcome, Administrator!");
console.log("You have full access.");
}Welcome, Administrator! You have full access.
Truthy and Falsy Values
In JavaScript, the condition doesn't have to be a strict boolean. JavaScript converts non-boolean values to boolean using type coercion.
Falsy Values (evaluate to false):
if (false) console.log("Won't print");
if (0) console.log("Won't print");
if (-0) console.log("Won't print");
if ("") console.log("Won't print");
if (null) console.log("Won't print");
if (undefined) console.log("Won't print");
if (NaN) console.log("Won't print");
console.log("None of the above printed!");None of the above printed!
Truthy Values (evaluate to true):
if (1) console.log("1 is truthy");
if ("hello") console.log("Non-empty string is truthy");
if ([]) console.log("Empty array is truthy");
if ({}) console.log("Empty object is truthy");
if (-1) console.log("Negative numbers are truthy");
if ("0") console.log("String '0' is truthy");1 is truthy Non-empty string is truthy Empty array is truthy Empty object is truthy Negative numbers are truthy String '0' is truthy
⚠️ Gotcha! Empty arrays[]and empty objects{}are truthy!
Multiple Conditions with Logical Operators
AND Operator (&&)
Both conditions must be true:
let age = 25;
let hasLicense = true;
if (age >= 18 && hasLicense) {
console.log("You can drive a car.");
}You can drive a car.
OR Operator (||)
At least one condition must be true:
It's the weekend!
NOT Operator (!)
Negates the condition:
let isLoggedIn = false;
if (!isLoggedIn) {
console.log("Please log in to continue.");
}Please log in to continue.
Combining Multiple Operators
let score = 85;
let attendance = 90;
let hasSubmittedProject = true;
if (score >= 80 && attendance >= 75 && hasSubmittedProject) {
console.log("Student passes with distinction!");
}Student passes with distinction!
Nested If Statements
You can place if statements inside other if statements:
let age = 20;
let hasID = true;
if (age >= 18) {
console.log("Age requirement met.");
if (hasID) {
console.log("ID verified. Entry granted!");
}
}Age requirement met. ID verified. Entry granted!
Single Line If Statement (Without Braces)
When there's only one statement, braces are optional:
let x = 10;
if (x > 5) console.log("x is greater than 5");x is greater than 5
⚠️ Best Practice: Always use curly braces even for single-line if statements to avoid bugs when adding more lines later.
Comparison Operators in If Statements
let a = 10;
let b = "10";
// Strict equality (checks value AND type)
if (a === 10) console.log("a is strictly equal to 10");
// Loose equality (checks value only, with type coercion)
if (a == b) console.log("a loosely equals b");
// Strict inequality
if (a !== b) console.log("a is not strictly equal to b");
// Greater than / Less than
if (a > 5) console.log("a is greater than 5");
if (a < 20) console.log("a is less than 20");
// Greater than or equal / Less than or equal
if (a >= 10) console.log("a is >= 10");
if (a <= 10) console.log("a is <= 10");a is strictly equal to 10 a loosely equals b a is not strictly equal to b a is greater than 5 a is less than 20 a is >= 10 a is <= 10
Practical Programs
Program 1: Check if a Number is Positive
let num = 7;
if (num > 0) {
console.log(num + " is a positive number.");
}7 is a positive number.
Program 2: Check Voting Eligibility
let voterAge = 17;
if (voterAge >= 18) {
console.log("You can vote.");
}
if (voterAge < 18) {
console.log("You cannot vote yet. Wait " + (18 - voterAge) + " more year(s).");
}You cannot vote yet. Wait 1 more year(s).
Program 3: Password Validation
Password length is acceptable. Password contains a special character. Password contains an uppercase letter. Password contains a number.
Program 4: Check if a Year is a Leap Year
2024 is a leap year.
Program 5: Array Element Check
The array is not empty. First fruit: apple Mango is available!
Program 6: Object Property Validation
let user = {
name: "John",
email: "john@example.com",
age: 25
};
if (user.name) {
console.log("Name: " + user.name);
}
if (user.email && user.email.includes("@")) {
console.log("Valid email: " + user.email);
}
if (user.age && user.age >= 18) {
console.log("User is an adult.");
}Name: John Valid email: john@example.com User is an adult.
Program 7: Check Even/Odd Number
let number = 42;
if (number % 2 === 0) {
console.log(number + " is an even number.");
}
if (number % 2 !== 0) {
console.log(number + " is an odd number.");
}42 is an even number.
❌ Common Mistakes
Mistake 1: Assignment Instead of Comparison
let x = 5;
// ❌ WRONG: This assigns 10 to x (always truthy)
if (x = 10) {
console.log("This always runs! x is now: " + x);
}
// ✅ CORRECT: This compares x with 10
x = 5;
if (x === 10) {
console.log("x equals 10");
} else {
console.log("x is not 10, it is:", x);
}This always runs! x is now: 10 x is not 10, it is: 5
Mistake 2: Using == Instead of ===
let value = "1";
// ❌ Loose comparison (type coercion happens)
if (value == 1) {
console.log("Loose: '1' == 1 is true (unexpected!)");
}
// ✅ Strict comparison (no type coercion)
if (value === 1) {
console.log("This won't print");
} else {
console.log("Strict: '1' !== 1 (different types)");
}Loose: '1' == 1 is true (unexpected!) Strict: '1' !== 1 (different types)
Mistake 3: Semicolon After If Condition
let score = 95;
// ❌ Semicolon ends the if statement prematurely
if (score > 90);
{
console.log("This ALWAYS runs regardless of condition!");
}This ALWAYS runs regardless of condition!
Mistake 4: Forgetting That Strings are Case-Sensitive
let input = "Yes";
// ❌ This won't match because of case
if (input === "yes") {
console.log("User said yes");
} else {
console.log("'Yes' !== 'yes' — case matters!");
}
// ✅ Convert to lowercase for comparison
if (input.toLowerCase() === "yes") {
console.log("User said yes (case-insensitive check)");
}'Yes' !== 'yes' — case matters! User said yes (case-insensitive check)
Best Practices
// ❌ Redundant comparison
if (isActive === true) { }
// ✅ Direct boolean usage
if (isActive) { }
// ❌ Hard to read
if (u.a >= 18 && u.s === "active" && u.r.includes("admin")) { }
// ✅ Easy to read with descriptive variables
let isAdult = user.age >= 18;
let isActive = user.status === "active";
let isAdmin = user.roles.includes("admin");
if (isAdult && isActive && isAdmin) {
console.log("Grant admin access");
}Grant admin access
🎤 Interview Questions
Q1. What is the difference between == and === in if conditions? > == (loose equality) performs type coercion before comparison, so "5" == 5 is true. === (strict equality) checks both value and type without coercion, so "5" === 5 is false. Always prefer ===.
Q2. What are falsy values in JavaScript? > There are 7 falsy values: false, 0, -0, "" (empty string), null, undefined, and NaN. Every other value is truthy, including empty arrays [] and empty objects {}.
Q3. Can an if statement exist without curly braces? > Yes, for a single statement. However, always using braces is best practice — adding a second line without braces later will cause bugs.
Q4. What happens if you use = instead of === in an if condition? > A single = is the assignment operator. It assigns the value and the condition evaluates the assigned value's truthiness. This is almost always a bug that's hard to find. Example: if (x = 5) always evaluates to true.
Q5. Is [] (empty array) truthy or falsy? > Truthy! Empty arrays and empty objects {} are truthy. Only the 7 specific falsy values listed above are falsy.
Q6. What is short-circuit evaluation? > With &&, if the first condition is false, the second is never evaluated. With ||, if the first is true, the second is never evaluated. Used for safe access: if (obj && obj.property).
Q7. What is a guard clause? > An if statement at the beginning of a function that returns early if a condition isn't met. It reduces nesting: if (!user) return; if (!user.isActive) return; // main logic.
Q8. What is the difference between if and the ternary operator? > The ternary operator (condition ? a : b) is an expression that returns a value. if is a statement. Ternary is best for simple value assignments; if for executing multiple statements.
Q9. How do you check if a variable is null or undefined? > Use if (value == null) — loose equality catches both null and undefined. Or if (value === null || value === undefined) for explicit checking.
Q10. Why is if ([] == false) true but if ([]) runs the block? > [] is truthy (non-null object), so if ([]) runs the block. But [] == false involves type coercion: [] becomes "" which becomes 0, and false becomes 0, so 0 == 0 is true. This is why === should always be preferred.
Q11. Can if conditions span multiple lines? > Yes! For readability:
if (
user.age >= 18 &&
user.status === "active" &&
user.subscription !== "expired"
) {
// code
}Q12. What is the output?
let x = "";
if (x) {
console.log("truthy");
} else {
console.log("falsy");
}falsy— empty string""is one of the 7 falsy values.
🔑 Key Takeaways
| Concept | Detail |
|---|---|
| Purpose | Run code only when condition is true |
| Falsy values | false, 0, -0, "", null, undefined, NaN |
| Truthy | Everything else (including [] and {}) |
| Best operator | Use === not == |
| Always use | {} even for single-line if |
| Avoid | Semicolon after if(condition) |
| Assignment bug | if (x = 5) assigns, not compares! |
💡 Remember: The if statement is your program's decision-maker. Master it and you control what your program does in every situation!Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript If Statement Tutorial – Complete Guide with Examples.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, control, flow, statement
Related JavaScript Master Course Topics