JavaScript Mastery - Conditional Statements


Mastering JavaScript control flow is essential for any web developer looking to create dynamic, interactive applications. In this comprehensive guide, we'll explore JavaScript's conditional operators and loop mechanisms in depth, providing practical examples that demonstrate their real-world applications.
1. Conditional Statements
Conditional statements allow your code to make decisions and execute different blocks based on specific conditions. These are the backbone of logical operations in any programming language.
1.1 if Statement
The if statement is the most fundamental conditional structure in JavaScript. It evaluates a condition and executes a block of code only when that condition is true. This simple but powerful construct forms the basis of decision-making in your programs.
Where to use in real life:
Form validation to check if user inputs meet specific criteria
Permission control to verify if a user has access to certain features
Feature toggling based on user preferences or system requirements
Syntax:
if (condition) {
// Code to execute when condition is true
}
Examples:
// Example 1: Checking user eligibility for discount
let userAge = 65;
if (userAge >= 60) {
console.log("Code Subtle offers senior citizen discount!");
}
// Output: Code Subtle offers senior citizen discount!
// Example 2: Check if a string is not empty
let name = "Code Subtle";
if (name !== "") {
console.log("Hello, " + name);
}
// Output: Hello, Code Subtle
// Example 3: Check if a number is even
let num = 8;
if (num % 2 === 0) {
console.log("The number is even");
}
// Output: The number is even
Tips & Tricks:
Always use curly braces even for single-line statements to improve readability and prevent bugs when adding more code later
Combine multiple conditions using logical operators (&&, ||) instead of nesting multiple if statements when possible
For complex conditions, consider storing the condition in a well-named variable for better readability
1.2 Else Statement
The else statement provides an alternative execution path when the if condition evaluates to false. It creates a binary decision structure that ensures one of two code blocks will always execute.
Where to use in real life:
User authentication flows (logged in vs. not logged in)
Error handling when an operation either succeeds or fails
Toggle functionality for UI elements (show/hide, enable/disable)
Syntax:
if (condition) {
// Code to execute when condition is true
} else {
// Code to execute when condition is false
}
Examples:
// Example 1: Check if a number is positive or negative
let number = -5;
if (number >= 0) {
console.log("The number is positive.");
} else {
console.log("The number is negative.");
}
// Output: The number is negative.
// Example 2: Compare two numbers
let a = 10;
let b = 15;
if (a > b) {
console.log("a is greater than b.");
} else {
console.log("b is greater than or equal to a.");
}
// Output: b is greater than or equal to a.
// Example 3: Check if a number is even or odd
let num = 7;
if (num % 2 === 0) {
console.log("The number is even.");
} else {
console.log("The number is odd.");
}
// Output: The number is odd.
Tips & Tricks:
Keep your if-else blocks concise and focused on a single responsibility
Consider using the ternary operator for simple if-else conditions, especially for assignments
Be careful of complex nested if-else structures; refactor them into functions when they grow too complex
1.3 else if Statement
The else if statement enables multiple conditional branches in your code. It creates a hierarchical decision structure where each condition is tested only if all previous conditions are false, allowing for more complex decision trees.
Where to use in real life:
Implementing different discount tiers based on purchase amounts
Handling various user roles and permissions in an application
Categorizing content based on multiple criteria (e.g., rating systems)
Syntax:
if (condition1) {
// Code block 1
} else if (condition2) {
// Code block 2
} else if (condition3) {
// Code block 3
} else {
// Default code block
}
Examples:
// Example 1: Age Group Identifier
let age = 25;
if (age < 13) {
console.log("Child");
} else if (age < 20) {
console.log("Teenager");
} else if (age < 60) {
console.log("Adult");
} else {
console.log("Senior Citizen");
}
// Output: Adult
// Example 2: Weather recommendations
let temperature = 28;
if (temperature < 0) {
console.log("Code Subtle advises: Wear heavy winter clothing");
} else if (temperature < 15) {
console.log("Code Subtle advises: A jacket would be appropriate");
} else if (temperature < 25) {
console.log("Code Subtle advises: Light clothing should be fine");
} else {
console.log("Code Subtle advises: Summer clothing recommended");
}
// Output: Code Subtle advises: Summer clothing recommended
// Example 3: Quiz score grading
let score = 72;
if (score >= 90) {
console.log("Code Subtle grades this as: A - Excellent");
} else if (score >= 70) {
console.log("Code Subtle grades this as: B - Good");
} else if (score >= 50) {
console.log("Code Subtle grades this as: C - Average");
} else if (score >= 35) {
console.log("Code Subtle grades this as: D - Below Average");
} else {
console.log("Code Subtle grades this as: F - Failed");
}
// Output: Code Subtle grades this as: B - Good
Tips & Tricks:
Order your conditions from most specific to most general for better performance and readability
When dealing with ranges, arrange conditions in ascending or descending order to avoid logic errors
For complex condition chains, consider using a switch statement or lookup tables instead
1.4 switch Statement
The switch statement provides an elegant way to compare a single expression against multiple possible case values. It's particularly efficient when evaluating a variable against many constant values, offering better readability than lengthy else-if chains.
Where to use in real life:
Menu systems where user selects from numbered options
State machines with discrete, known states
Error code handling with different actions for specific codes
Syntax:
switch (expression) {
case value1:
// code block 1
break;
case value2:
// code block 2
break;
default:
// default code block
}
Examples:
// Example 1: HTTP status code handling
let statusCode = 404;
switch (statusCode) {
case 200:
console.log("Code Subtle: Request successful");
break;
case 404:
console.log("Code Subtle: Resource not found");
break;
case 500:
console.log("Code Subtle: Server error occurred");
break;
default:
console.log("Code Subtle: Unknown status code");
}
// Output: Code Subtle: Resource not found
// Example 2: Day of the Week
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
console.log(dayName);
// Output: Wednesday
// Example 3: Calculator (Add, Subtract, Multiply, Divide)
let a = 10;
let b = 5;
let operator = "*";
let result;
switch (operator) {
case "+":
result = a + b;
break;
case "-":
result = a - b;
break;
case "*":
result = a * b;
break;
case "/":
result = a / b;
break;
default:
result = "Invalid operator";
}
console.log(result);
// Output: 50
Tips & Tricks:
Always include a default case to handle unexpected values
Be careful with fall-through behavior if you omit the break statement intentionally
Switch statements use strict equality (===) for comparisons, so be mindful of type differences
1.5 Ternary Operator
The ternary operator provides a concise way to write simple if-else statements, resulting in more compact code. It's ideal for straightforward conditional expressions, especially when assigning values conditionally.
Where to use in real life:
Conditional rendering in UI frameworks like React
Setting default values in function parameters
Simple toggle states or flag assignments
Syntax:
condition ? expressionIfTrue : expressionIfFalse
Examples:
// Example 1: Check if a number is even or odd
let num = 7;
let result = (num % 2 === 0) ? "Even" : "Odd";
console.log(result);
// Output: "Odd"
// Example 2: Compare two numbers
let a = 10, b = 15;
let larger = (a > b) ? a : b;
console.log("Larger number is:", larger);
// Output: "Larger number is: 15"
// Example 3: Set default value if input is empty
let input = "";
let output = (input !== "") ? input : "Code Subtle";
console.log(output);
// Output: "Code Subtle"
Tips & Tricks:
Avoid nesting multiple ternary operators as it makes code difficult to read
For readability, use parentheses to group complex conditions within ternary expressions
Consider moving to if-else when the expressions become lengthy or complex
1.6 Nested if-else Statement
Nested if-else statements create hierarchical decision trees, where one conditional statement exists inside another. This structure allows for complex, multi-level conditional logic when simpler structures aren't sufficient.
Where to use in real life:
Multi-factor authentication flows
Complex form validation with interdependent fields
Game logic with multiple conditional states
Syntax:
if (condition1) {
if (condition2) {
// Code for condition1 AND condition2 both true
} else {
// Code for condition1 true, condition2 false
}
} else {
if (condition3) {
// Code for condition1 false, condition3 true
} else {
// Code for condition1 false, condition3 false
}
}
Examples:
// Example 1: Number Type Checker (Positive/Negative, Even/Odd)
let num = -8;
if (num > 0) {
if (num % 2 === 0) {
console.log("Positive even number");
} else {
console.log("Positive odd number");
}
} else {
if (num < 0) {
if (num % 2 === 0) {
console.log("Negative even number");
} else {
console.log("Negative odd number");
}
} else {
console.log("Number is zero");
}
}
//Output: Negative even number
// Example 2: Ticket pricing system
let age = 15;
let isStudent = true;
let isWeekend = false;
if (age < 12) {
console.log("Code Subtle: Child ticket - $8");
} else {
if (isStudent) {
if (isWeekend) {
console.log("Code Subtle: Student weekend ticket - $12");
} else {
console.log("Code Subtle: Student weekday ticket - $10");
}
} else {
if (isWeekend) {
console.log("Code Subtle: Adult weekend ticket - $15");
} else {
console.log("Code Subtle: Adult weekday ticket - $13");
}
}
}
// Output: Code Subtle: Student weekday ticket - $10
// Example 3: Traffic Light Decision
let light = "red";
let emergency = false;
if (light === "green") {
console.log("Go!");
} else {
if (light === "yellow") {
console.log("Slow down.");
} else {
if (light === "red") {
if (emergency) {
console.log("Proceed with caution (emergency).");
} else {
console.log("Stop.");
}
} else {
console.log("Invalid signal.");
}
}
}
// Output: Stop
Tips & Tricks:
Consider refactoring deeply nested if-else statements into separate functions for readability
Use early returns or guard clauses to reduce nesting depth
Look for opportunities to use logical operators (&&, ||) to combine conditions instead of nesting
2. Truthy and Falsy Values
In JavaScript, every value has an inherent boolean context. When a value is evaluated in a boolean context (like in an if
statement or logical operation), it's either considered "truthy" (acts like true
) or "falsy" (acts like false
).
This concept is essential because JavaScript performs automatic type coercion, converting values to booleans when needed.
2.1 List of Falsy Values
JavaScript has exactly 8 falsy values. Memorizing these is crucial:
false
- The boolean false0
- Zero-0
- Negative zero0n
- BigInt zero""
(empty string) - Empty string literalsnull
- Represents intentional absence of valueundefined
- Variable declared but not assignedNaN
- Not a Number
// All of these are falsy
console.log(Boolean(false)); // false
console.log(Boolean(0)); // false
console.log(Boolean(-0)); // false
console.log(Boolean(0n)); // false
console.log(Boolean("")); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(NaN)); // false
2.2 Truthy Values
Any value that isn't in the falsy list above is considered truthy. This includes some values that might surprise you:
// All of these are truthy
console.log(Boolean("0")); // true (string containing zero)
console.log(Boolean("false")); // true (string containing "false")
console.log(Boolean([])); // true (empty array)
console.log(Boolean({})); // true (empty object)
console.log(Boolean(function(){})); // true (function)
console.log(Boolean(-1)); // true (negative number)
console.log(Boolean(42)); // true (positive number)
console.log(Boolean("hello")); // true (non-empty string)
console.log(Boolean(Infinity)); // true
console.log(Boolean(-Infinity)); // true
2.3 Practical Examples in Conditional Statements
Understanding truthy and falsy values becomes critical when writing conditional logic:
let username = "";
let age = 0;
let isLoggedIn = false;
let data = null;
if (username) {
console.log("Welcome, " + username);
} else {
console.log("Please enter a username"); // This will execute
}
if (age) {
console.log("Age: " + age);
} else {
console.log("Age not provided"); // This will execute
}
if (isLoggedIn) {
console.log("Access granted");
} else {
console.log("Please log in"); // This will execute
}
Subscribe to my newsletter
Read articles from Code Subtle directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Code Subtle
Code Subtle
At Code Subtle, we empower aspiring web developers through personalized mentorship and engaging learning resources. Our community bridges the gap between theory and practice, guiding students from basics to advanced concepts. We offer expert mentorship and write interactive, user-friendly articles on all aspects of web development. Join us to learn, grow, and build your future in tech!