Conditional statements allow your code to make decisions and execute different blocks of code based on specific conditions. They're the foundation of program logic and enable your applications to respond dynamically to different situations.
Simple If Statement
The if statement executes code only when a condition is true.
let temperature = 75;
if (temperature > 70) {
console.log("It's warm outside!");
}
The else clause provides an alternative when the condition is false.
Example of else
The else clause provides an alternative when the condition is false.
let age = 16;
if (age >= 18) {
console.log("You can vote!");
} else {
console.log("You're not old enough to vote yet.");
}
You can nest conditionals for more complex logic.
Example of Nested if/else
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else {
if (score >= 80) {
console.log("Grade: B");
} else {
console.log("Grade: C or below");
}
}
When you have multiple exclusive conditions to check, else if creates cleaner, more readable code than nested if statements.
Example of Else If Chains
let hour = 14;
if (hour < 12) {
console.log("Good morning!");
} else if (hour < 18) {
console.log("Good afternoon!");
} else if (hour < 22) {
console.log("Good evening!");
} else {
console.log("Good night!");
}
Real-World Example: Grade Calculator
function calculateGrade(score) {
if (score >= 90) {
return "A - Excellent!";
} else if (score >= 80) {
return "B - Good job!";
} else if (score >= 70) {
return "C - Satisfactory";
} else if (score >= 60) {
return "D - Needs improvement";
} else {
return "F - Please see instructor";
}
}
console.log(calculateGrade(87));
Comparison operators evaluate relationships between values and return boolean results (true or false).
Equality Operators
// Loose equality (==) - converts types before comparing
console.log(5 == "5"); // true (string converted to number)
console.log(0 == false); // true (false converted to 0)
// Strict equality (===) - checks both value AND type
console.log(5 === "5"); // false (different types)
console.log(5 === 5); // true (same value and type)
Inequality operators
console.log(5 != "5"); // false (loose inequality)
console.log(5 !== "5"); // true (strict inequality)
Relational Operators
let x = 10;
let y = 20;
console.log(x > y); // false (greater than)
console.log(x < y); // true (less than)
console.log(x >= 10); // true (greater than or equal)
console.log(y <= 15);Logical operators allow you to combine multiple conditions into more complex expressions.
Returns true only if ALL conditions are true.
Example:
let age = 25;
let hasLicense = true;
if (age >= 16 && hasLicense) {
console.log("You can drive!");
}
Practical example: Form validation
let username = "john_doe";
let password = "secure123";
if (username.length > 3 && password.length >= 8) {
console.log("Valid credentials");
}
Returns true if AT LEAST ONE condition is true.
Example:
let day = "Saturday";
if (day === "Saturday" || day === "Sunday") {
console.log("It's the weekend!");
}
Inverts a boolean value (true becomes false, false becomes true).
Example:
let isRaining = false;
if (!isRaining) {
console.log("No umbrella needed!");
}
// Checking if something is NOT equal
let status = "inactive";
if (status !== "active") {
console.log("Account is not active");
}
Combining Logical Operators
let age = 25;
let isStudent = true;
let hasID = true;
// Complex condition
if ((age >= 18 && hasID) || isStudent) {
console.log("Discount eligible");
}
Truthy and Falsy Values
Only six values are falsy in JavaScript:
if (false) { } // false
if (0) { } // zero
if ("") { } // empty string
if (null) { } // null
if (undefined) { } // undefined
if (NaN) { } // Not a Number
// None of these code blocks will execute
Everything else is truthy, including:
Truthy Values
if (true) { } // boolean true
if (1) { } // any non-zero number
if (-1) { } // negative numbers
if ("hello") { } // non-empty strings
if ("0") { } // string containing zero
if ("false") { } // string "false"
if ([]) { } // empty array
if ({}) { } // empty object
if (function() {}) { } // functions
Checking if a variable has a value:
let userName = "";
if (userName) {
console.log(`Welcome, ${userName}!`);
} else {
console.log("Please enter your name");
}
Default values with OR operator:
function greet(name) {
let displayName = name || "Guest";
console.log(`Hello, ${displayName}!`);
}
greet("Alice"); // "Hello, Alice!"
greet(""); // "Hello, Guest!"
greet(); // "Hello, Guest!"
Short-circuit evaluation:
let user = null;
// Safely access properties
if (user && user.isAdmin) {
console.log("Admin access granted");
}
// If user is null /undefined, the second part never executes
Ternary Operator
// Syntax: condition ? value If True : value If False
let age = 20;
let status = age >= 18 ? "adult" : "minor";
console.log(status); // "adult"
Traditional if/else equivalent
let status2;
if (age >= 18) {
status2 = "adult";
} else {
status2 = "minor";
}
Exercise 1: Traffic Light System
function trafficLight(color) {
if (color === "red") {
return "Stop";
} else if (color === "yellow") {
return "Slow down";
} else if (color === "green") {
return "Go";
} else {
return "Invalid color";
}
}
Exercise 1: Traffic Light System
Exercise 2: Login Validator
function validateLogin(username, password) {
if (!username || !password) {
return "Username and password required";
} else if (username.length < 4) {
return "Username too short";
} else if (password.length < 8) {
return "Password too short";
} else {
return "Login successful";
}
}