Back to JavaScript Fundamentals

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.
4 min readLogan FordLogan Ford

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 true
3}

Let's break down a practical example:


1// Example 1: Basic if statement
2const temperature = 25;
3
4if (temperature > 30) {
5 console.log("It's a hot day!");
6}
7
8// Example 2: Using multiple conditions
9const isWeekend = true;
10const isRaining = false;
11
12if (isWeekend && !isRaining) {
13 console.log("Perfect day for outdoor activities!");
14}
15
16// Example 3: Checking string values
17const userRole = "admin";
18
19if (userRole === "admin") {
20 console.log("Welcome to the admin panel");
21}

Common Gotchas and Best Practices

  1. Truthy vs Falsy Values:

1// Be careful with truthy/falsy values
2if (0) {
3 console.log("This won't run"); // 0 is falsy
4}
5
6if ("") {
7 console.log("This won't run"); // empty string is falsy
8}
9
10if ([]) {
11 console.log("This will run!"); // empty array is truthy
12}
13
14// Better to be explicit
15if (array.length > 0) {
16 console.log("Array has items");
17}

  1. Single Line if Statements:
1// While this works:
2if (temperature > 30) console.log("Hot!");
3
4// 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 example
2const score = 85;
3const isPremiumUser = true;
4
5if (score >= 90) {
6 console.log("A Grade");
7} else if (score >= 80) {
8 console.log("B Grade");
9
10 // Nested if statements for more complex logic
11 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}
20
21// Real-world example: User authentication
22const user = {
23 isLoggedIn: true,
24 role: "editor",
25 subscription: "pro"
26};
27
28if (!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

  1. Arrange your conditions from most specific to least specific
  2. Use early returns for better performance
  3. Consider using switch statements for many conditions
  4. 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";
2
3switch (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}
17
18// 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 values
2console.log(5 == "5"); // true (converts types)
3
4// Strictly equal to (===) - compares values and types
5console.log(5 === "5"); // false (different types)
6
7// Greater than (>)
8console.log(10 > 5); // true
9
10// Less than (<)
11console.log(5 < 10); // true
12
13// Greater than or equal to (>=)
14console.log(5 >= 5); // true
15
16// Less than or equal to (<=)
17console.log(4 <= 5); // true
18
19// Not equal to (!=)
20console.log(5 != "6"); // true

Logical Operators

Combine multiple conditions using logical operators:

1// AND operator (&&) - both conditions must be true
2const age = 25;
3const hasLicense = true;
4
5if (age >= 18 && hasLicense) {
6 console.log("You can drive!"); // This will run
7}
8
9// OR operator (||) - at least one condition must be true
10const isWeekend = false;
11const isHoliday = true;
12
13if (isWeekend || isHoliday) {
14 console.log("No work today!"); // This will run
15}
16
17// NOT operator (!) - reverses a boolean value
18const isLoggedIn = false;
19
20if (!isLoggedIn) {
21 console.log("Please log in"); // This will run
22}

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}
10
11// Example usage
12validateEmail('[email protected]'); // Valid
13validateEmail('invalid-email'); // Invalid

2. User Authentication

1const user = {
2 isLoggedIn: true,
3 role: 'admin',
4 subscription: 'premium'
5};
6
7// Check user access level
8if (!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

  1. Use Clear Conditions

    • Write conditions that are easy to understand
    • Break complex conditions into smaller parts
    • Use meaningful variable names
  2. Default Cases

    • Always include else or default cases
    • Handle unexpected scenarios
  3. Use Strict Equality

    • Prefer === over == to avoid type coercion
    • Be explicit about your comparisons
  4. 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:

  1. Write a function that determines if a number is positive, negative, or zero
  2. Create a simple grade calculator (A, B, C, D, F)
  3. 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
Beginner
JavascriptFunctionsConditionals
Check if a Number is a Multiple of Another Number
Beginner
JavascriptFunctionsConditionals+1

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.

Share this article