Main menu

Pages

Conditional Statements in JavaScript: Making Decisions in Your Code

1. Introduction

Conditional statements are an essential component of JavaScript programming that allow you to make decisions and control the flow of your code based on specific conditions. They enable you to execute different blocks of code, handle various scenarios, and customize user experiences.

In this guide, you will explore and practice working with conditional statements in JavaScript. You will encounter common use cases where conditional statements play a crucial role, such as age verification, temperature evaluation, grade calculation, determining odd or even numbers, and leap year calculation.

2. Understanding Boolean Logic

2.1. Introduction to Boolean data type

In JavaScript, the Boolean data type is a fundamental concept for understanding conditional statements. A Boolean value represents either true or false. It is named after mathematician George Boole, who developed the Boolean algebra, which forms the basis of modern digital logic and programming.

Boolean values are crucial in decision-making because they allow us to determine the truth or falsehood of a condition. The Boolean data type in JavaScript is represented by the keywords true and false. For example, a variable can be assigned a Boolean value as follows:


let isRaining = true;
let isSunny = false;


When we assign a variable as either true or false, we can indicate whether a condition is satisfied or not. This becomes crucial when determining the flow of our code based on specific conditions.

2.2. Comparison operators in JavaScript

To evaluate conditions and make decisions, JavaScript provides a set of comparison operators. These operators allow us to compare values and determine their relationship. Here are the commonly used comparison operators in JavaScript:

  • Equal to (==): Checks if two values are equal, regardless of their data types.
  • Not equal to (!=): Checks if two values are not equal.
  • Strict equal to (===): Checks if two values are equal in both value and data type.
  • Strict not equal to (!==): Checks if two values are not equal in either value or data type.
  • Greater than (>): Checks if the left operand is greater than the right operand.
  • Less than (<): Checks if the left operand is less than the right operand.
  • Greater than or equal to (>=): Checks if the left operand is greater than or equal to the right operand.
  • Less than or equal to (<=): Checks if the left operand is less than or equal to the right operand.

When we use these comparison operators, we can create conditions that evaluate to true or false, providing the foundation for decision-making in JavaScript.

2.3. Evaluating conditions and returning boolean values

In JavaScript, conditions are evaluated based on their truthiness or falsiness. When a condition is evaluated, it returns a boolean value, either true or false. This is the key mechanism behind conditional statements.

Conditions can be formed by combining variables, values, and comparison operators. For example, let's consider the following code snippet:


let age = 25;
let isAdult = age >= 18;


In this example, we evaluate the condition age >= 18, which checks if the value of the variable age is greater than or equal to 18. The result of this evaluation is assigned to the variable isAdult. If the condition is true, isAdult will be assigned the value true; otherwise, it will be assigned the value false.

The ability to evaluate conditions and obtain boolean values allows us to control the flow of our program based on specific circumstances. We can use these boolean values in conjunction with conditional statements, such as if statements or switch statements, to make decisions and execute different blocks of code accordingly.

3. if Statement

3.1. Syntax and usage of the if statement


if (condition) {
  // Code to be executed if the condition is true
}


The condition inside the parentheses is evaluated, and if it resolves to true, the code block within the curly braces is executed. If the condition is false, the code block is skipped, and the program continues to the next statement.

3.2. Writing simple if statements

Simple if statements are used when we want to execute a block of code based on a single condition. Let's consider an example:


let hour = 15;

if (hour < 12) {
  console.log("Good morning!");
}


In this example, if the value of the variable hour is less than 12, the message "Good morning!" will be printed to the console. Otherwise, if the condition is false, the code block is not executed.

3.3. Handling multiple conditions with if-else statements

In situations where we have multiple conditions and need to execute different blocks of code based on each condition, we can use if-else statements. The syntax is as follows:


if (condition1) {
  // Code to be executed if condition1 is true
} else {
  // Code to be executed if condition1 is false
}


Let's consider an example:


let score = 75;

if (score >= 90) {
  console.log("Excellent!");
} else {
  console.log("Keep up the good work!");
}


In this case, if the value of the variable score is greater than or equal to 90, the message "Excellent!" is printed. Otherwise, if the condition is false, the message "Keep up the good work!" is printed.

3.4. Nesting if statements for complex conditions

When dealing with complex conditions, we can nest if statements within one another. This allows us to evaluate multiple conditions and execute different blocks of code accordingly. Here's an example:


let num = 10;

if (num > 0) {
  if (num % 2 === 0) {
    console.log("The number is positive and even.");
  } else {
    console.log("The number is positive and odd.");
  }
} else {
  console.log("The number is either zero or negative.");
}


In this example, we check if the number is positive or negative. If it's positive, we further check if it's even or odd. The appropriate message is then printed based on the conditions.

3.5. Using the else-if ladder for multiple options

In scenarios where we have multiple options or conditions to evaluate, we can use the else-if ladder. It allows us to test multiple conditions in sequence until one of them is true. Here's an example:


let dayOfWeek = "Tuesday";

if (dayOfWeek === "Monday") {
  console.log("Start of the week!");
} else if (dayOfWeek === "Tuesday") {
  console.log("Second day of the week!");
} else if (dayOfWeek === "Wednesday") {
  console.log("Middle of the week!");
} else {
  console.log("It's another day of the week.");
}


In this case, depending on the value of dayOfWeek, the corresponding message is printed. The else-if ladder provides a way to handle multiple options and execute the appropriate code block based on the first matching condition.

4. Logical Operators

4.1. Exploring logical operators: &&, ||, !

Logical operators in JavaScript are powerful tools for combining and manipulating conditions. They allow us to perform logical operations on boolean values and make more complex decisions in our code. There are three main logical operators: && (logical AND), || (logical OR), and ! (logical NOT).

4.2 Combining conditions with logical AND (&&) operator


let age = 25;
let hasLicense = true;

if (age >= 18 && hasLicense) {
  console.log("You are eligible to drive!");
} else {
  console.log("You are not eligible to drive.");
}


In this example, both age >= 18 and hasLicense must evaluate to true for the condition to be true and print the message "You are eligible to drive!". If either of the conditions is false, the else block is executed.

4.3. Using logical OR (||) operator for alternative conditions


let isStudent = true;
let isEmployee = false;

if (isStudent || isEmployee) {
  console.log("You are part of the organization.");
} else {
  console.log("You are not affiliated with the organization.");
}


In this example, if either isStudent or isEmployee is true, the condition is true and prints the message "You are part of the organization.". If both conditions are false, the else block is executed.

4.4. Negating conditions with logical NOT (!) operator


let isAuthenticated = false;

if (!isAuthenticated) {
  console.log("Please log in to access the content.");
} else {
  console.log("Welcome to the member's area!");
}


In this example, the logical NOT operator negates the value of isAuthenticated. If it is false, the condition becomes true, and the message "Please log in to access the content." is printed. If isAuthenticated is true, the else block is executed.

Note: These logical operators provide flexibility and control in your code, allowing you to handle various scenarios and conditions with ease.

5. Switch Statement

5.1. Syntax and structure of the switch statement

The switch statement in JavaScript provides a concise way to handle multiple cases or conditions. It evaluates an expression and executes the code block that matches the evaluated value. The syntax of a switch statement is as follows:


switch (expression) {
  case value1:
    // Code to be executed if expression matches value1
    break;
  case value2:
    // Code to be executed if expression matches value2
    break;
  // Additional cases...
  default:
    // Code to be executed if expression doesn't match any case
}


The expression is evaluated once, and its value is compared to the values in the cases. If a match is found, the corresponding code block is executed. If no match is found, the code block under default is executed (optional).

5.2. Writing switch statements for multi-case scenarios

Switch statements are particularly useful when dealing with multi-case scenarios. Let's consider an example:


let dayOfWeek = "Monday";

switch (dayOfWeek) {
  case "Monday":
    console.log("It's the start of the week!");
    break;
  case "Tuesday":
  case "Wednesday":
  case "Thursday":
    console.log("It's a weekday.");
    break;
  case "Friday":
    console.log("It's finally Friday!");
    break;
  case "Saturday":
  case "Sunday":
    console.log("It's the weekend!");
    break;
  default:
    console.log("Invalid day.");
}


In this example, based on the value of dayOfWeek, the switch statement evaluates the matching case and executes the corresponding code block. For instance, if dayOfWeek is "Monday", the message "It's the start of the week!" is printed.

5.3. Adding a default case for unmatched conditions

Adding a default case to a switch statement allows you to handle unmatched conditions. If the expression doesn't match any of the cases, the code block under the default label is executed. Let's see an example:


let fruit = "banana";

switch (fruit) {
  case "apple":
    console.log("It's an apple.");
    break;
  case "orange":
    console.log("It's an orange.");
    break;
  default:
    console.log("It's a fruit, but I'm not sure which one.");
}


In this example, if fruit is neither "apple" nor "orange", the code block under the default label is executed, printing the message "It's a fruit, but I'm not sure which one."

5.4. Using break and fall-through to control switch flow

The break statement is crucial in a switch statement. It terminates the current case and prevents fall-through, where execution continues to the next case. Let's illustrate this with an example:


let num = 2;

switch (num) {
  case 1:
    console.log("It's one.");
    break;
  case 2:
    console.log("It's two.");
    // Fall-through intentionally
  case 3:
    console.log("It's either two or three.");
    break;
  default:
    console.log("It's a different number.");
}


In this example, when num is 2, the message "It's two." is printed. However, notice the intentional fall-through from case 2 to case 3. The message "It's either two or three." is also printed. To avoid fall-through, a break statement is placed after the code block of each case.

Note: The switch statement provides a concise and organized way to execute specific code blocks based on the evaluated value of an expression. Experiment with different cases and conditions to harness the power of switch statements in your code.

6. Ternary Operator

6.1. Understanding the ternary operator syntax

The ternary operator in JavaScript is a concise way to write conditional expressions. It allows us to evaluate a condition and return one of two expressions based on the result. The syntax of the ternary operator is as follows:


condition ? expression1 : expression2


The condition is evaluated, and if it's true, expression1 is returned. Otherwise, if the condition is false, expression2 is returned. The ternary operator condenses an if-else statement into a single line, making the code more compact and readable.

6.2. Writing concise conditional expressions with the ternary operator

The ternary operator is particularly useful when we need to assign a value or perform a simple operation based on a condition. Let's see an example:


let isMorning = true;
let greeting = isMorning ? "Good morning!" : "Hello!";
console.log(greeting);


In this example, the ternary operator evaluates the condition isMorning. If it's true, the value "Good morning!" is assigned to the variable greeting. Otherwise, if the condition is false, the value "Hello!" is assigned. The resulting value is then printed to the console. The ternary operator allows us to achieve the same result as an if-else statement, but with more concise code.

6.3. Implementing nested ternary operators

Nested ternary operators can be used when we have multiple conditions and need to return different expressions based on those conditions. Although nesting too many ternary operators can reduce code readability, they can be useful in certain scenarios. Let's consider an example:


let temperature = 25;
let weatherCondition = temperature > 30 ? "Hot" : temperature > 20 ? "Warm" : "Cool";
console.log("The weather is " + weatherCondition);


In this example, we evaluate the temperature to determine the weather condition. If the temperature is greater than 30, the value "Hot" is assigned. Otherwise, if the temperature is greater than 20, the value "Warm" is assigned. If neither condition is true, the value "Cool" is assigned. The final weather condition is then printed to the console.

Note: It's important to use nested ternary operators judiciously, considering code readability and maintainability. In some cases, using a traditional if-else statement or refactoring the logic may be a better approach.

The ternary operator is a powerful tool for simple conditions and can significantly improve code efficiency when used appropriately.

7. Common Use Cases and Examples

7.1. Checking user input validity

One common use case for conditional statements in JavaScript is checking the validity of user input. When building interactive applications or forms, it's essential to validate the data entered by the user. When we use conditional statements, we can perform checks and provide feedback or take appropriate actions. Let's consider an example:


let userInput = "12345";
let isValid = false;

if (userInput.length === 5 && !isNaN(userInput)) {
  isValid = true;
}

if (isValid) {
  console.log("User input is valid.");
} else {
  console.log("Invalid input. Please enter a 5-digit number.");
}


In this example, we check if the user input has a length of 5 and is a number by using the length property and isNaN function. If the condition is true, we set the isValid variable to true. Based on the value of isValid, we provide feedback to the user, indicating whether the input is valid or invalid.

7.2. Handling different outcomes based on conditions

Conditional statements are often used to handle different outcomes based on specific conditions. This can include executing different blocks of code or performing specific actions based on certain criteria. Let's explore an example:


let time = 20;

if (time < 12) {
  console.log("Good morning!");
} else if (time < 18) {
  console.log("Good afternoon!");
} else {
  console.log("Good evening!");
}


In this scenario, based on the value of time, we greet the user with a different message. If the time is less than 12, the message "Good morning!" is displayed. If the time is between 12 and 18, the message "Good afternoon!" is shown. Otherwise, if none of the previous conditions are met, the message "Good evening!" is printed.

7.3. Validating form data

Another practical use case for conditional statements is form data validation. When users submit forms on a website, it's important to validate the data to ensure it meets specific requirements or constraints. Let's see an example:


function validateForm() {
  let name = document.getElementById("name").value;
  let email = document.getElementById("email").value;

  if (name === "") {
    alert("Please enter your name.");
    return false;
  }

  if (email === "" || !email.includes("@")) {
    alert("Please enter a valid email address.");
    return false;
  }

  // Additional form validation logic...

  return true;
}


In this example, a JavaScript function is used to validate a form. The function retrieves the values entered in the name and email fields. It then performs conditional checks to ensure that both fields are filled in and that the email contains the "@" symbol. If any of the conditions fail, an alert is displayed, and the function returns false to prevent form submission.

7.4. Controlling program flow based on conditions

Conditional statements are essential for controlling the flow of a program based on specific conditions. They allow us to make decisions and determine the execution path of our code. Let's consider an example:


let isLoggedIn = true;

if (isLoggedIn) {
  // Perform authorized actions
  console.log("You are logged in. Access granted.");
} else {
  // Display login prompt
  console.log("Please log in to access this feature.");
}


In this scenario, based on the value of isLoggedIn, the program determines whether to execute authorized actions or prompt the user to log in. The conditional statement directs the flow of the program, enabling different code blocks to be executed based on the condition.

7.5. Customizing user experiences with conditional statements

Conditional statements are invaluable for customizing user experiences in JavaScript applications. When we evaluate certain conditions, we can dynamically display content, provide personalized features, or tailor the user interface based on user-specific criteria. Let's explore an example:


let userType = "premium";

if (userType === "premium") {
  // Show premium content or features
  console.log("Welcome, premium user! Enjoy exclusive content.");
} else {
  // Display basic features or content
  console.log("Welcome! Explore our available content.");
}


In this example, based on the value of userType, we customize the user experience. If the user is a "premium" user, we provide access to exclusive content or features. Otherwise, for non-premium users or other user types, we display basic features or content. This conditional statement enables us to tailor the user experience based on user privileges or subscriptions.

8. Exercises: Conditional Statements in JavaScript

Task 1: Age Verification

Write a program that prompts the user to enter their age. Based on the provided age, display the appropriate message:

  • If the age is less than 18, display "You are not eligible."
  • If the age is between 18 and 65 (inclusive), display "You are eligible."
  • If the age is greater than 65, display "You are eligible with limitations."

Task 2: Temperature Evaluation

Write a program that prompts the user to enter the temperature in Celsius. Based on the provided temperature, display the appropriate message:

  • If the temperature is below freezing (less than 0 degrees), display "It's freezing outside!"
  • If the temperature is between 0 and 15 degrees, display "It's chilly."
  • If the temperature is between 16 and 25 degrees, display "It's moderate."
  • If the temperature is above 25 degrees, display "It's hot!"

Task 3: Grade Calculation

Write a program that prompts the user to enter their exam score. Based on the provided score, display the corresponding grade:

  • If the score is 90 or above, display "A".
  • If the score is between 80 and 89 (inclusive), display "B".
  • If the score is between 70 and 79 (inclusive), display "C".
  • If the score is between 60 and 69 (inclusive), display "D".
  • If the score is below 60, display "F".

Task 4: Odd or Even

Write a program that prompts the user to enter a number. Determine whether the entered number is odd or even. Display the appropriate message accordingly:

  • If the number is odd, display "The number is odd."
  • If the number is even, display "The number is even."

Task 5: Leap Year Calculation

Write a program that prompts the user to enter a year. Determine whether the entered year is a leap year or not. Display the appropriate message accordingly:

  • If the year is a leap year, display "It's a leap year!"
  • If the year is not a leap year, display "It's not a leap year."

Note: Remember to use conditional statements such as if statements, if-else statements, or switch statements to implement the required functionality.

9. Solutions : Conditional Statements in JavaScript

Task 1: Age Verification


let age = prompt("Please enter your age:");

if (age < 18) {
  console.log("You are not eligible.");
} else if (age >= 18 && age <= 65) {
  console.log("You are eligible.");
} else {
  console.log("You are eligible with limitations.");
}


Explanation: In this task, we prompt the user to enter their age using the prompt() function. We then use an if-else if-else statement to evaluate the entered age and display the corresponding message. If the age is less than 18, the message "You are not eligible." is printed. If the age is between 18 and 65 (inclusive), the message "You are eligible." is printed. If the age is greater than 65, the message "You are eligible with limitations." is printed.

Task 2: Temperature Evaluation


let temperature = prompt("Please enter the temperature in Celsius:");

if (temperature < 0) {
  console.log("It's freezing outside!");
} else if (temperature >= 0 && temperature <= 15) {
  console.log("It's chilly.");
} else if (temperature >= 16 && temperature <= 25) {
  console.log("It's moderate.");
} else {
  console.log("It's hot!");
}


Explanation: In this task, we prompt the user to enter the temperature in Celsius. Using an if-else if-else statement, we evaluate the entered temperature and display the appropriate message. If the temperature is below 0 degrees, the message "It's freezing outside!" is printed. If the temperature is between 0 and 15 degrees (inclusive), the message "It's chilly." is printed. If the temperature is between 16 and 25 degrees (inclusive), the message "It's moderate." is printed. If the temperature is above 25 degrees, the message "It's hot!" is printed.

Task 3: Grade Calculation


let score = prompt("Please enter your exam score:");

if (score >= 90) {
  console.log("A");
} else if (score >= 80 && score <= 89) {
  console.log("B");
} else if (score >= 70 && score <= 79) {
  console.log("C");
} else if (score >= 60 && score <= 69) {
  console.log("D");
} else {
  console.log("F");
}


Explanation: In this task, we prompt the user to enter their exam score. Using an if-else if-else statement, we evaluate the entered score and display the corresponding grade. If the score is 90 or above, the grade "A" is printed. If the score is between 80 and 89 (inclusive), the grade "B" is printed. If the score is between 70 and 79 (inclusive), the grade "C" is printed. If the score is between 60 and 69 (inclusive), the grade "D" is printed. If the score is below 60, the grade "F" is printed.

Task 4: Odd or Even


let number = prompt("Please enter a number:");

if (number % 2 === 0) {
  console.log("The number is even.");
} else {
  console.log("The number is odd.");
}


Explanation: In this task, we prompt the user to enter a number. Using the modulus operator (%), we check if the entered number is divisible by 2. If the remainder is 0, it means the number is even, and the message "The number is even." is printed. If the remainder is not 0, it means the number is odd, and the message "The number is odd." is printed.

Task 5: Leap Year Calculation


let year = prompt("Please enter a year:");

if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
  console.log("It's a leap year!");
} else {
  console.log("It's not a leap year.");
}


Explanation: In this task, we prompt the user to enter a year. Using conditional statements and the modulus operator (%), we determine whether the entered year is a leap year. A leap year is divisible by 4, except for years divisible by 100, unless they are also divisible by 400. If the conditions for a leap year are satisfied, the message "It's a leap year!" is printed. If the conditions are not met, the message "It's not a leap year." is printed.

10. Encouragement

Thank you for investing your time in reading this guide! I trust that you have found it informative and beneficial in enhancing your comprehension of JavaScript conditional statements.

Ultimately, I strongly urge you to continue your learning journey by delving into the next guide [JavaScript Loops Demystified: A Deep Dive into Iteration ]. Thank you once more, and I look forward to meeting you in the next guide

Comments