JavaScript Notes
Learn the JavaScript if statement from scratch with syntax, flowcharts, truthy/falsy values, real-world examples, common mistakes, and interview Q&A for beginners.
The if statement is the most fundamental decision-making tool in JavaScript. It runs a block of code only when a condition is true — skipping it entirely if the condition is false.
Simple definition: "IF this is true, THEN do this."
📝 Syntax
if (condition) {
// This code runs ONLY when condition is true
}condition— any expression that evaluates totrueorfalse- Parentheses
()— required around the condition - Curly braces
{}— define the block to execute when true
💡 Real World Analogy
Analogy: Think of an if statement like a bouncer at a club:
- "IF the person is 18 or older → let them in"
- If they're under 18 → they simply don't enter (nothing happens)
The bouncer doesn't kick anyone out or do anything special for underage people — they just don't let them in (condition is false → block is skipped).
✅ Basic Examples
Example 1: Check if Age Qualifies to Vote
let age = 20;
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 (Block is Skipped)
let temperature = 20;
if (temperature > 40) {
console.log("It's extremely hot! Stay indoors.");
}
console.log("Temperature check done.");Temperature check done.
Since 20 > 40 is false, the if block was completely skipped.
Example 3: Check a String Value
let username = "admin";
if (username === "admin") {
console.log("Welcome, Administrator!");
console.log("You have full access to the system.");
}Welcome, Administrator! You have full access to the system.
🔬 Truthy and Falsy Values
JavaScript doesn't always need a strict true/false — it evaluates any value as truthy (acts like true) or falsy (acts like false).
Falsy Values — These Make the if Block SKIP
// All of these are FALSY — if block will NOT run
if (false) console.log("false"); // won't print
if (0) console.log("0"); // won't print
if (-0) console.log("-0"); // won't print
if ("") console.log("empty string");// won't print
if (null) console.log("null"); // won't print
if (undefined) console.log("undefined"); // won't print
if (NaN) console.log("NaN"); // won't print
console.log("None of the if blocks ran!");None of the if blocks ran!
Truthy Values — These Make the if Block RUN
if (1) console.log("1 is truthy");
if (-1) console.log("-1 is truthy");
if ("hello") console.log("Non-empty string is truthy");
if ("0") console.log("String '0' is truthy");
if ([]) console.log("Empty array is truthy");
if ({}) console.log("Empty object is truthy");1 is truthy -1 is truthy Non-empty string is truthy String '0' is truthy Empty array is truthy Empty object is truthy
⚠️ Gotcha! An empty array[]and empty object{}are truthy in JavaScript! Only the 7 falsy values above are falsy.
🔗 Logical Operators in If Conditions
AND Operator && — Both must be true
let age = 25;
let hasLicense = true;
if (age >= 18 && hasLicense) {
console.log("You can drive. ✓");
}You can drive. ✓
OR Operator || — At least one must be true
It's the weekend! 🎉
NOT Operator ! — Reverses the condition
let isLoggedIn = false;
if (!isLoggedIn) {
console.log("Please log in to continue.");
}Please log in to continue.
Combining Multiple Operators
let score = 88;
let attendance = 80;
let hasProject = true;
if (score >= 75 && attendance >= 70 && hasProject) {
console.log("Student qualifies for certificate! 🎓");
}Student qualifies for certificate! 🎓
📊 Comparison Operators Used in If
let a = 10;
let b = "10";
if (a === 10) console.log("a === 10 → strict equal (value + type match)");
if (a == b) console.log("a == b → loose equal (only value match)");
if (a !== b) console.log("a !== b → strict NOT equal");
if (a > 5) console.log("a > 5 → greater than");
if (a < 20) console.log("a < 20 → less than");
if (a >= 10) console.log("a >= 10 → greater than or equal");
if (a <= 10) console.log("a <= 10 → less than or equal");a === 10 → strict equal (value + type match) a == b → loose equal (only value match) a !== b → strict NOT equal a > 5 → greater than a < 20 → less than a >= 10 → greater than or equal a <= 10 → less than or equal
🏗️ Practical Programs
Program 1: Check Positive, Negative, or Zero
let num = -7;
if (num > 0) {
console.log(num + " is positive.");
}
if (num < 0) {
console.log(num + " is negative.");
}
if (num === 0) {
console.log(num + " is zero.");
}-7 is negative.
Program 2: Leap Year Check
2024 is a leap year. 📅
Program 3: Check If Array is Non-Empty
Your cart has 3 items. First item: Apple
Program 4: Password Strength Checker
✓ Password length is good (8+ characters) ✓ Contains uppercase letter ✓ Contains a number ✓ Contains a special character
❌ Common Mistakes
Mistake 1: Assignment = Instead of Comparison ===
let x = 5;
// ❌ WRONG — this ASSIGNS 10 to x (always true!)
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("This runs only if x is 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: Semicolon After the if Condition
let score = 95;
// ❌ WRONG — semicolon creates an empty if body
if (score >= 90); // ← semicolon here ends the if!
{
console.log("This ALWAYS runs, condition doesn't matter!");
}
// ✅ CORRECT — no semicolon
if (score >= 90) {
console.log("Excellent score!");
}This ALWAYS runs, condition doesn't matter! Excellent score!
Mistake 3: Using == Instead of === (Type Coercion Surprise)
let input = "5"; // string from user input
// ❌ Might behave unexpectedly
if (input == 5) {
console.log("Loose: '5' == 5 is TRUE (coercion happened)");
}
// ✅ Explicit and safe
if (input === "5") {
console.log("Strict: '5' === '5' is TRUE");
}
if (Number(input) === 5) {
console.log("Explicitly converted to number, then compared");
}Loose: '5' == 5 is TRUE (coercion happened) Strict: '5' === '5' is TRUE Explicitly converted to number, then compared
🧩 Practice Problems
Problem 1: Determine if a number is divisible by both 3 and 5
let n = 15;
if (n % 3 === 0 && n % 5 === 0) {
console.log(n + " is divisible by both 3 and 5");
}15 is divisible by both 3 and 5
Problem 2: Check if a string is a valid email
let email = "user@example.com";
if (email.includes("@") && email.includes(".")) {
console.log("Looks like a valid email format ✓");
}Looks like a valid email format ✓
Problem 3: Bank withdrawal check
let balance = 5000;
let withdrawal = 3000;
if (balance >= withdrawal) {
balance -= withdrawal;
console.log(`Withdrawal successful! Remaining balance: ₹${balance}`);
}Withdrawal successful! Remaining balance: ₹2000
🎤 Interview Questions
Q1. What is an if statement in JavaScript? > An if statement evaluates a condition and executes a code block only when that condition is truthy. If the condition is falsy, the block is skipped.
Q2. What are falsy values in JavaScript? > The 7 falsy values are: false, 0, -0, "" (empty string), null, undefined, and NaN. All other values are truthy.
Q3. Is [] (empty array) truthy or falsy? > Truthy! Empty arrays and empty objects {} are truthy in JavaScript. Only the 7 specific falsy values evaluate to false.
Q4. What's the difference between == and === in an if condition? > == (loose equality) allows type coercion — e.g., "5" == 5 is true. === (strict equality) requires both value AND type to match — "5" === 5 is false. Always prefer === to avoid unexpected behavior.
Q5. What happens if you put a semicolon after the if condition? > if (condition); creates an empty if body. The block in curly braces that follows always executes regardless of the condition. This is a subtle bug.
Q6. Can you write an if statement without curly braces? > Yes, for a single statement: if (x > 0) console.log("positive");. But it's a best practice to always use curly braces to avoid bugs when adding more lines later.
Q7. What is the output?
let x = 0;
if (x) {
console.log("truthy");
}
console.log("after if");after ifonly —0is falsy, so the if block is skipped.
🔑 Key Takeaways
| Concept | Detail |
|---|---|
| Purpose | Execute code only when condition is true |
| Falsy values | false, 0, "", null, undefined, NaN, -0 |
| Truthy | Everything else (including [] and {}) |
| Best practice | Always use === for comparisons |
| Best practice | Always use {} even for single-line if |
| Avoid | Semicolon after if(condition) |
💡 Remember: The if statement is the gateway to decision-making in code. Master it and you can control what your program does in any situation!Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript If Statement Tutorial – Conditional Logic 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, javascript if statement tutorial – conditional logic with examples
Related JavaScript Master Course Topics