What are JavaScript Conditionals?
Learn how to use if, else, switch statements and more with practical examples. JavaScript conditionals are the building blocks of decision-making in programming.

Introduction to JavaScript Conditionals
Conditional statements are the building blocks of decision-making in programming. They allow your code to make choices and execute different actions based on different conditions. Think of them as the "if-then" logic you use in everyday life: "If it's raining, then I'll take an umbrella."
The if Statement
The if
statement is the fundamental building block of conditional logic in JavaScript. It allows your code to make decisions by executing code blocks only when certain conditions are met. Understanding if
statements is crucial for writing dynamic and responsive code.
Basic Syntax and Usage
The basic syntax follows this pattern:
1if (condition) {2 // code to execute if condition is true3}
Let's break down a practical example:
1// Example 1: Basic if statement2const temperature = 25;34if (temperature > 30) {5 console.log("It's a hot day!");6}78// Example 2: Using multiple conditions9const isWeekend = true;10const isRaining = false;1112if (isWeekend && !isRaining) {13 console.log("Perfect day for outdoor activities!");14}1516// Example 3: Checking string values17const userRole = "admin";1819if (userRole === "admin") {20 console.log("Welcome to the admin panel");21}
Common Gotchas and Best Practices
- Truthy vs Falsy Values:
1// Be careful with truthy/falsy values2if (0) {3 console.log("This won't run"); // 0 is falsy4}56if ("") {7 console.log("This won't run"); // empty string is falsy8}910if ([]) {11 console.log("This will run!"); // empty array is truthy12}1314// Better to be explicit15if (array.length > 0) {16 console.log("Array has items");17}
- Single Line if Statements:
1// While this works:2if (temperature > 30) console.log("Hot!");34// This is better for readability:5if (temperature > 30) {6 console.log("Hot!");7}
Using else and else if
The else
and else if
statements extend the power of conditionals by allowing you to handle multiple scenarios. They create a decision tree where only one branch will execute.
Basic Structure
1// Complex decision tree example2const score = 85;3const isPremiumUser = true;45if (score >= 90) {6 console.log("A Grade");7} else if (score >= 80) {8 console.log("B Grade");910 // Nested if statements for more complex logic11 if (isPremiumUser) {12 console.log("Eligible for advanced courses");13 }14} else if (score >= 70) {15 console.log("C Grade");16} else {17 console.log("Need improvement");18 console.log("Contact a tutor for help");19}2021// Real-world example: User authentication22const user = {23 isLoggedIn: true,24 role: "editor",25 subscription: "pro"26};2728if (!user.isLoggedIn) {29 console.log("Please log in to continue");30} else if (user.role === "admin") {31 console.log("Welcome to the admin dashboard");32} else if (user.role === "editor" && user.subscription === "pro") {33 console.log("Welcome to the pro editor dashboard");34} else {35 console.log("Welcome to the basic dashboard");36}
Performance Tips
- Arrange your conditions from most specific to least specific
- Use early returns for better performance
- Consider using switch statements for many conditions
- Avoid deeply nested if/else statements (consider early returns or switch statements instead)
Switch Statements
When you have multiple conditions to check against a single value, the switch
statement can be cleaner than multiple if/else
statements:
1const dayOfWeek = "Monday";23switch (dayOfWeek) {4 case "Monday":5 console.log("Start of the work week!");6 break;7 case "Friday":8 console.log("Weekend is coming!");9 break;10 case "Saturday":11 case "Sunday":12 console.log("It's the weekend!");13 break;14 default:15 console.log("It's a regular day.");16}1718// Output: "Start of the work week!"19// The switch statement checks the value of dayOfWeek against each case
Comparison Operators
JavaScript provides several operators to compare values:
1// Equal to (==) - compares values2console.log(5 == "5"); // true (converts types)34// Strictly equal to (===) - compares values and types5console.log(5 === "5"); // false (different types)67// Greater than (>)8console.log(10 > 5); // true910// Less than (<)11console.log(5 < 10); // true1213// Greater than or equal to (>=)14console.log(5 >= 5); // true1516// Less than or equal to (<=)17console.log(4 <= 5); // true1819// Not equal to (!=)20console.log(5 != "6"); // true
Logical Operators
Combine multiple conditions using logical operators:
1// AND operator (&&) - both conditions must be true2const age = 25;3const hasLicense = true;45if (age >= 18 && hasLicense) {6 console.log("You can drive!"); // This will run7}89// OR operator (||) - at least one condition must be true10const isWeekend = false;11const isHoliday = true;1213if (isWeekend || isHoliday) {14 console.log("No work today!"); // This will run15}1617// NOT operator (!) - reverses a boolean value18const isLoggedIn = false;1920if (!isLoggedIn) {21 console.log("Please log in"); // This will run22}
Common Use Cases
Here are some practical examples of using conditionals in real applications:
1. Form Validation
1function validateEmail(email) {2 if (email.includes('@') && email.includes('.')) {3 console.log('Email format is valid');4 return true;5 } else {6 console.log('Please enter a valid email');7 return false;8 }9}1011// Example usage12validateEmail('[email protected]'); // Valid13validateEmail('invalid-email'); // Invalid
2. User Authentication
1const user = {2 isLoggedIn: true,3 role: 'admin',4 subscription: 'premium'5};67// Check user access level8if (!user.isLoggedIn) {9 console.log('Please log in to continue');10} else if (user.role === 'admin') {11 console.log('Welcome, admin!');12} else if (user.subscription === 'premium') {13 console.log('Welcome, premium user!');14} else {15 console.log('Welcome, basic user!');16}
Best Practices
-
Use Clear Conditions
- Write conditions that are easy to understand
- Break complex conditions into smaller parts
- Use meaningful variable names
-
Default Cases
- Always include else or default cases
- Handle unexpected scenarios
-
Use Strict Equality
- Prefer === over == to avoid type coercion
- Be explicit about your comparisons
-
Keep it Simple
- Avoid deeply nested conditions
- Consider using early returns
- Break complex logic into functions
Practice Examples
Try these exercises to improve your understanding:
- Write a function that determines if a number is positive, negative, or zero
- Create a simple grade calculator (A, B, C, D, F)
- Build a basic calculator with different operations
Here are some practice questions to test your knowledge:
Check if a Number is Positive, Negative, or Zero in JavaScript
Check if a Number is a Multiple of Another Number
Ready to master JavaScript? Join TechBlitz for daily coding challenges, personalized learning paths, and a supportive community of developers. Start your journey today at TechBlitz.
Learn to code, faster
Join 810+ developers who are accelerating their coding skills with TechBlitz.