Open In App

Conditional Statements in JavaScript

Last Updated : 15 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript Conditional statements allow you to execute specific blocks of code based on conditions. If the condition meets then a particular block of action will be executed otherwise it will execute another block of action that satisfies that particular condition.

There are several methods that can be used to perform Conditional Statements in JavaScript.

  • if statement: Executes a block of code if a specified condition is true.
  • else statement: Executes a block of code if the same condition of the preceding if statement is false.
  • else if statement: Adds more conditions to the if statement, allowing for multiple alternative conditions to be tested.
  • switch statement: Evaluates an expression, then executes the case statement that matches the expression’s value.
  • ternary operator (conditional operator): Provides a concise way to write if-else statements in a single line.
  • Nested if else statement: Allow for multiple conditions to be checked in a hierarchical manner.

JavaScript Conditional statements Examples:

1. Using if Statement

The if statement is used to evaluate a particular condition. If the condition holds true, the associated code block is executed.

Syntax:

if ( condition ) {
// If the condition is met,
//code will get executed.
}

Example: In this example, we are using the if statement to find given number is even or odd.

Javascript
let num = 20;

if (num % 2 === 0) {
    console.log("Given number is even number.");
}

if (num % 2 !== 0) {
    console.log("Given number is odd number.");
};

Output
Given number is even number.

Explanation: This JavaScript code determines if the variable `num` is even or odd using the modulo operator `%`. If `num` is divisible by 2 without a remainder, it logs “Given number is even number.” Otherwise, it logs “Given number is odd number.”

2. Using if-else Statement

The if-else statement will perform some action for a specific condition. Here we are using the else statement in which the else statement is written after the if statement and it has no condition in their code block.

Syntax:

if (condition1) {
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true
}
}

Example: In this example, we are using if-else conditional statement to check the driving licence eligibility date.

Javascript
let age = 25;

if (age >= 18) {
    console.log("You are eligible of driving licence")
} else {
    console.log("You are not eligible for driving licence")
};

Output
You are eligible of driving licence

Explanation: This JavaScript code checks if the variable `age` is greater than or equal to 18. If true, it logs “You are eligible for a driving license.” Otherwise, it logs “You are not eligible for a driving license.” This indicates eligibility for driving based on age.

3. else if Statement

The else if statement in JavaScript allows handling multiple possible conditions and outputs, evaluating more than two options based on whether the conditions are true or false.

Syntax:

if (1st condition) {
// Code for 1st condition
} else if (2nd condition) {
// ode for 2nd condition
} else if (3rd condition) {
// Code for 3rd condition
} else {
// ode that will execute if all
// above conditions are false
}

Example: In this example, we are using the above-explained approach.

Javascript
const num = 0;

if (num > 0) {
    console.log("Given number is positive.");
} else if (num < 0) {
    console.log("Given number is negative.");
} else {
    console.log("Given number is zero.");
};

Output
Given number is zero.

Explanation: This JavaScript code determines whether the constant `num` is positive, negative, or zero. If `num` is greater than 0, it logs “Given number is positive.” If `num` is less than 0, it logs “Given number is negative.” If neither condition is met (i.e., `num` is zero), it logs “Given number is zero.”

4. Using Switch Statement (JavaScript Switch Case)

As the number of conditions increases, you can use multiple else-if statements in JavaScript. but when we dealing with many conditions, the switch statement may be a more preferred option.

Syntax:

switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
. . .
case valueN:
statementN;
break;
default:
statementDefault;
};

Example: In this example, we find a branch name Based on the student’s marks, this switch statement assigns a specific engineering branch to the variable Branch. The output displays the student’s branch name,

Javascript
const marks = 85;

let Branch;

switch (true) {
    case marks >= 90:
        Branch = "Computer science engineering";
        break;
    case marks >= 80:
        Branch = "Mechanical engineering";
        break;
    case marks >= 70:
        Branch = "Chemical engineering";
        break;
    case marks >= 60:
        Branch = "Electronics and communication";
        break;
    case marks >= 50:
        Branch = "Civil engineering";
        break;
    default:
        Branch = "Bio technology";
        break;
}

console.log(`Student Branch name is : ${Branch}`);

Output
Student Branch name is : Mechanical engineering

Explanation:

This JavaScript code assigns a branch of engineering to a student based on their marks. It uses a switch statement with cases for different mark ranges. The student’s branch is determined according to their marks and logged to the console.

5. Using Ternary Operator ( ?: )

The conditional operator, also referred to as the ternary operator (?:), is a shortcut for expressing conditional statements in JavaScript.

Syntax:

condition ? value if true : value if false

Example: In this example, we use the ternary operator to check if the user’s age is 18 or older. It prints eligibility for voting based on the condition.

Javascript
let age = 21;

const result =
    (age >= 18) ? "You are eligible to vote."
        : "You are not eligible to vote.";

console.log(result);

Output
You are eligible to vote.

Explanation: This JavaScript code checks if the variable `age` is greater than or equal to 18. If true, it assigns the string “You are eligible to vote.” to the variable `result`. Otherwise, it assigns “You are not eligible to vote.” The value of `result` is then logged to the console.

6. Nested if…else

Nested if…else statements in JavaScript allow us to create complex conditional logic by checking multiple conditions in a hierarchical manner. Each if statement can have an associated else block, and within each if or else block, you can nest another if…else statement. This nesting can continue to multiple levels, but it’s important to maintain readability and avoid excessive complexity.

Syntax:

if (condition1) {
// Code block 1
if (condition2) {
// Code block 2
} else {
// Code block 3
}
} else {
// Code block 4
}

Example: This example demonstrates how nested if…else statements can be used to handle different scenarios based on multiple conditions.

JavaScript
let weather = "sunny";
let temperature = 25;

if (weather === "sunny") {
    if (temperature > 30) {
        console.log("It's a hot day!");
    } else if (temperature > 20) {
        console.log("It's a warm day.");
    } else {
        console.log("It's a bit cool today.");
    }
} else if (weather === "rainy") {
    console.log("Don't forget your umbrella!");
} else {
    console.log("Check the weather forecast!");
};

Output
It's a warm day.

Explanation: In this example, the outer if statement checks the weather variable. If it’s “sunny,” it further checks the temperature variable to determine the type of day it is (hot, warm, or cool). Depending on the values of weather and temperature, different messages will be logged to the console.

Conditional Statements in JavaScript Use-Cases:

1. JavaScript if-else

JavaScript if-else or conditional statements will perform some action for a specific condition.

2. Control Statements in JavaScript

Control Statements are used to control the flow of the program with the help of conditional statements.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads