SimpleTuts.com

JavaScript Conditional Statements

Conditional statements are fundamental in JavaScript for making decisions in the code. These statements allow you to execute certain blocks of code based on whether a specified condition is true or false.

Types of Conditional Statements

1. if Statement

The if statement executes a block of code if a specified condition is true.

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

Example:

let age = 18;
if (age >= 18) {
    console.log("You are an adult."); // Outputs: You are an adult.
}

2. if...else Statement

The if...else statement executes one block of code if the condition is true, and another block of code if the condition is false.

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

Example:

let age = 16;
if (age >= 18) {
    console.log("You are an adult.");
} else {
    console.log("You are a minor."); // Outputs: You are a minor.
}

3. else if Statement

The else if statement allows you to specify a new condition if the first condition is false.

if (condition1) {
    // Code to be executed if condition1 is true
} else if (condition2) {
    // Code to be executed if condition2 is true
} else {
    // Code to be executed if both conditions are false
}

Example:

let score = 85;
if (score >= 90) {
    console.log("Grade A");
} else if (score >= 75) {
    console.log("Grade B"); // Outputs: Grade B
} else {
    console.log("Grade C");
}

4. switch Statement

The switch statement evaluates an expression and executes code blocks based on the matching case. It is often used as an alternative to multiple else if statements.

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

Example:

let day = 3;
switch (day) {
    case 1:
        console.log("Monday");
        break;
    case 2:
        console.log("Tuesday");
        break;
    case 3:
        console.log("Wednesday"); // Outputs: Wednesday
        break;
    default:
        console.log("Another day");
}