Loading...
Loading...

Conditional Statements in JavaScript

Conditional statements allow you to execute certain blocks of code based on specific conditions. JavaScript provides several types of conditional statements, including if, else, else if, and switch.

Using the If Statement

let temperature = 30;

if (temperature > 25) {
    console.log("It's a hot day!");
}

In this example, the message "It's a hot day!" will be logged to the console if the temperature is greater than 25.

Using the If...Else Statement

let temperature = 20;

if (temperature > 25) {
    console.log("It's a hot day!");
} else {
    console.log("It's a cool day!");
}

Here, if the temperature is not greater than 25, the message "It's a cool day!" will be displayed instead.

Using Else If for Multiple Conditions

let temperature = 15;

if (temperature > 25) {
    console.log("It's a hot day!");
} else if (temperature > 15) {
    console.log("It's a warm day!");
} else {
    console.log("It's a cool day!");
}

This example checks multiple conditions and executes the corresponding block based on the temperature value.

Using the Switch Statement

let fruit = "apple";

switch (fruit) {
    case "banana":
        console.log("Banana is yellow.");
        break;
    case "apple":
        console.log("Apple is red or green.");
        break;
    case "grape":
        console.log("Grapes are purple.");
        break;
    default:
        console.log("Unknown fruit.");
}

In this example, the switch statement checks the value of fruit and executes the corresponding case. If none of the cases match, the default case will run.

Conclusion

Conditional statements are essential for controlling the flow of execution in JavaScript programs. By using if, else, else if, and switch, you can make your code responsive to different conditions and inputs.

0 Interaction
2.4K Views
Views
50 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home