JavaScript Lesson 5: Conditions
Conditions in JavaScript work similarly to Python but use curly braces instead of indentation. The logic is the same.
if / else if / else
const hour = 14; // 2 PM
if (hour < 12) {
console.log("Good morning!");
} else if (hour < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
Switch Statement
const day = "Monday";
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
console.log("Weekday - time to work!");
break;
case "Saturday":
case "Sunday":
console.log("Weekend - time to relax!");
break;
default:
console.log("Invalid day");
}
Truthy and Falsy
// Falsy values (behave like false in conditions):
// false, 0, -0, "", null, undefined, NaN
// Truthy: everything else
const userName = "";
if (userName) {
console.log("Welcome,", userName);
} else {
console.log("Please enter your name");
}
// Useful patterns:
const items = [];
if (items.length) {
console.log("Has items");
} else {
console.log("Empty!");
}
Nullish Coalescing (??)
// ?? returns right side only if left is null or undefined
const user = null;
const name = user ?? "Guest"; // "Guest"
const score = 0;
const points = score ?? 100; // 0 (not 100!)
// Because ?? only triggers for null/undefined, not 0
// Contrast with ||:
const pts2 = score || 100; // 100 (0 is falsy!)
🏋️ Practice Task
Create a simple login checker. Set username = “admin” and password = “secret123”. Ask for input using prompt() in the browser console. Check if both match and log “Login successful” or “Invalid credentials”.
💡 Hint: prompt() shows a popup in the browser. Use === to compare strings strictly.