DEV Community

Lokesh
Lokesh

Posted on

Conditional Statements in JavaScript

What Are Conditional Statements?

Conditional statements allow us to execute different blocks of code depending on whether a condition is true or false.

For example, we can check whether a person is eligible to vote based on their age.

JavaScript provides different conditional statements to make decisions in our programs.

1. if Statement

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

let age = 20;

if (age >= 18) {
    console.log("Eligible to vote");
}
Enter fullscreen mode Exit fullscreen mode

Output:

Eligible to vote
Enter fullscreen mode Exit fullscreen mode

Here, the condition age >= 18 is true, so the message is displayed.

2. if...else Statement

The if...else statement allows us to choose between two blocks of code.

let age = 16;

if (age >= 18) {
    console.log("Eligible to vote");
} else {
    console.log("Not eligible to vote");
}
Enter fullscreen mode Exit fullscreen mode

Output:

Not eligible to vote
Enter fullscreen mode Exit fullscreen mode

If the condition is true, the if block runs. Otherwise, the else block runs.

3. else if Statement

We use else if when we need to check multiple conditions.

let mark = 75;

if (mark >= 90) {
    console.log("Grade A");
} else if (mark >= 70) {
    console.log("Grade B");
} else if (mark >= 50) {
    console.log("Grade C");
} else {
    console.log("Fail");
}
Enter fullscreen mode Exit fullscreen mode

Output:

Grade B
Enter fullscreen mode Exit fullscreen mode

JavaScript checks the conditions from top to bottom and executes the first matching block.

4. switch Statement

The switch statement is useful when we want to compare one value against several possible cases.

let day = 2;

switch (day) {
    case 1:
        console.log("Monday");
        break;
    case 2:
        console.log("Tuesday");
        break;
    case 3:
        console.log("Wednesday");
        break;
    default:
        console.log("Invalid day");
}
Enter fullscreen mode Exit fullscreen mode

Output:

Tuesday
Enter fullscreen mode Exit fullscreen mode

The break statement stops execution from continuing into the next case. The default block runs when no case matches.

Why Are Conditional Statements Important?

Conditional statements help us:

  • Make decisions in our programs.
  • Check whether a user is eligible for something.
  • Assign grades based on marks.
  • Validate user input.
  • Control how a program behaves in different situations.

Top comments (0)