DEV Community

Pranay Rebeyro
Pranay Rebeyro

Posted on

Conditional Statements in JavaScript

Conditional Statements
Conditional statements allow JavaScript to execute different blocks of code based on whether a condition is true or false.

if statement

if - The if statement executes a block of code only if the condition is true.

let age = 20;

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

if else statement

  1. if...else - Use if...else when you want one block of code to run if the condition is true and another block if it's false.
let age = 16;

if (age >= 18) {
    console.log("Eligible to vote");
} else {
    console.log("Not eligible to vote");
} // Output: Not eligible to vote

Enter fullscreen mode Exit fullscreen mode

if elif statement

  1. if...else if...else - Use this when you have multiple conditions to check.
let marks = 85;

if (marks >= 90) {
    console.log("Grade A");
} else if (marks >= 75) {
    console.log("Grade B");
} else if (marks >= 50) {
    console.log("Grade C");
} else {
    console.log("Fail");
} // Output: Grade B
Enter fullscreen mode Exit fullscreen mode

switch statement

  1. switch statement - The switch statement is used when you have many possible values for one variable.
let day = 3;

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");
} // Output: Wednesday

// Important: The break statement stops the execution after the matching case.We must compulsory to use break statement because if you don't use break, JavaScript will continue executing the next cases even the output is correct.
Enter fullscreen mode Exit fullscreen mode

Nested if statement

  1. Nested if statement - You can also write an if statement inside another if.
let age = 20;
let hasLicense = true;

if (age >= 18) {
    if (hasLicense) {
        console.log("You can drive.");
    }
} // Output: You can drive.
Enter fullscreen mode Exit fullscreen mode

Ternary Operator

  1. Ternary Operator - An optimized one-line shorthand for standard if...else blocks
let isLoggedIn = true;
let systemMessage = isLoggedIn ? "Welcome back!" : "Please log in.";

console.log(systemMessage); // Outputs: Welcome back!
Enter fullscreen mode Exit fullscreen mode

Top comments (0)