JS If-Else Statements

Overview

The if...else statement is a fundamental control structure in JavaScript that allows you to execute different code blocks based on a specified condition. It enables your program to make decisions and choose between alternative actions.


Basic Syntax

The basic syntax of an if...else statement is as follows:

Try yourself
        
            
if (condition) {
    // Code to execute if condition is true
} else {
    // Code to execute if condition is false
}

        
    

Example

Let's consider an example where we want to determine if a given number is even or odd:

Try yourself
        
            
let number = 42;

if (number % 2 === 0) {
    console.log('The number is even.');
} else {
    console.log('The number is odd.');
}

        
    

Nested If-Else

It's possible to have multiple if...else statements nested within each other. This allows for more complex decision-making.

Try yourself
        
            
let x = 10;

if (x > 5) {
    if (x < 15) {
        console.log('x is between 5 and 15.');
    } else {
        console.log('x is greater than or equal to 15.');
    }
} else {
    console.log('x is less than or equal to 5.');
}

        
    

Summary

The if...else statement is a critical control structure in JavaScript, enabling your program to make decisions based on specified conditions. Understanding how to structure and use if...else statements is fundamental for writing effective and responsive JavaScript code.