JavaScript Conditional Statements

Understanding Conditional Statements

Conditional statements control behavior in JavaScript and determine whether or not pieces of code can run. They are essential for making decisions in your code based on different conditions.

In JavaScript, the most commonly used conditional statements include:

These structures allow you to perform different actions for different decisions. JavaScript evaluates the condition and executes the corresponding block of code when the condition is true. If no conditions are true, JavaScript can execute an else block of code, providing a default action.

Practical Examples

Using if

This example uses an if statement to check if a score is above 70. If the condition is true, it prints 'Passing grade' to the console:

let score = 75;
        if (score > 70) {
            console.log('Passing grade');
        }

Using else

Here, an if statement checks if the temperature is greater than 25 degrees. If not, the else part executes, printing 'It's cool outside':

let temperature = 20;
        if (temperature > 25) {
            console.log('It\'s warm outside');
        } else {
            console.log('It\'s cool outside');
        }

Using else if

This example demonstrates a chain of decisions starting with an if condition, followed by an else if, and ending with an else. It checks the time of day and greets accordingly:

let hours = 12;
        if (hours < 12) {
            console.log('Good morning');
        } else if (hours < 18) {
            console.log('Good afternoon');
        } else {
            console.log('Good evening');
        }

Using switch

The switch statement is used for more complex decision structures and is particularly useful when there are many cases to consider. This example uses switch to print the day of the week based on the numeric day:

let day = 3;
        switch (day) {
            case 1:
                console.log('Monday');
                break;
            case 2:
                console.log('Tuesday');
                break;
            case 3:
                console.log('Wednesday');
                break;
            case 4:
                console.log('Thursday');
                break;
            case 5:
                console.log('Friday');
                break;
            case 6:
                console.log('Saturday');
                break;
            case 7:
                console.log('Sunday');
                break;
            default:
                console.log('Invalid day');
        }

These examples demonstrate how conditional statements are used to make decisions in JavaScript, helping your program respond dynamically to different conditions and inputs.

Try it Yourself

Enter a number to check if it's positive, negative, or zero:

Test Your Knowledge: JavaScript Conditional Statements

Which statement is used to execute some code if 'i' is NOT equal to 5?