📌 Understanding the if Statement in JavaScript
The if statement allows JavaScript to execute a block of code only if a condition is
true.
🔹 Basic Example
var x = prompt("Where does the Pope live?");
if (x === "Vatican") {
alert("Correct!");
}
✔️ The prompt() asks the user a question and stores the response in x.
✔️ The if statement checks if x is exactly equal (===) to "Vatican".
✔️ If the condition is true, the alert "Correct!" is displayed.
✔️ If the user enters anything else, nothing happens.
🔹 Understanding === vs ==
=== (Strict Equality) → Checks both value and data type.
== (Loose Equality) → Converts data types if needed before comparison.
🚨 Example: == vs ===
console.log(5 == "5"); // ✅ true (Loose equality converts "5" to number)
console.log(5 === "5"); // ❌ false (Strict equality checks type too)
✔️ Using === prevents unintended type conversion bugs.
🔹 Using Variables in if Statements
var correctAnswer = "Vatican";
if (x === correctAnswer) {
alert("Correct!");
}
✔️ This makes the code easier to update and maintain.
🔹 Multiple Actions When Condition is True
You can execute multiple statements inside the if block:
var correctAnswer = "Vatican";
if (x === correctAnswer) {
score++; // Increase score
userIQ = "genius"; // Set IQ level
alert("Correct!");
}
✔️ All statements inside the {} execute if the condition is met.
🔹 if Without {} for One-Liners
If there is only one statement, curly brackets {} can be omitted:
if (x === "Vatican") alert("Correct!");
✔️ Legal but not recommended for readability.
🔹 Handling Case Sensitivity
If the user types "vatican" instead of "Vatican", the check fails.
To make it case-insensitive:
if (x.toLowerCase() === "vatican") {
alert("Correct!");
}
✔️ .toLowerCase() converts user input to lowercase before checking.
🔹 Handling Multiple Correct Answers
if (x === "Vatican" || x === "The Vatican") {
alert("Correct!");
}
✔️ || (OR operator) allows multiple valid responses.
💡 Quick Summary
✔️ if executes code only if the condition is true.
✔️ Use === instead of == for strict comparison.
✔️ Curly brackets {} can be omitted for one-liners (not recommended).
✔️ Use .toLowerCase() for case-insensitive comparisons.
✔️ Use || to allow multiple correct answers.