If else in Javascript



In JavaScript, the `if...else` statement is used for conditional execution of code. It allows you to execute different blocks of code depending on whether a specified condition is true or false. Here's a detailed lesson on `if...else` in JavaScript with examples:

### Basic `if...else` Statement:

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

```javascript
if (condition) {
    // code to be executed if the condition is true
} else {
    // code to be executed if the condition is false
}
```

### Example 1: Simple If...Else Statement

```javascript
let temperature = 25;

if (temperature > 30) {
    console.log("It's a hot day!");
} else {
    console.log("It's not too hot today.");
}
```

In this example, the code checks whether the temperature is greater than 30. If it is, it prints "It's a hot day!"; otherwise, it prints "It's not too hot today."

### Example 2: If...Else If...Else Statement

You can chain multiple conditions using `else if`:

```javascript
let hour = 14;

if (hour < 12) {
    console.log("Good morning!");
} else if (hour < 18) {
    console.log("Good afternoon!");
} else {
    console.log("Good evening!");
}
```

This example greets the user based on the time of the day.

### Example 3: Nested If...Else Statements

You can nest `if...else` statements to handle more complex conditions:

```javascript
let num = 10;

if (num > 0) {
    if (num % 2 === 0) {
        console.log("The number is positive and even.");
    } else {
        console.log("The number is positive and odd.");
    }
} else if (num === 0) {
    console.log("The number is zero.");
} else {
    console.log("The number is negative.");
}
```

This example classifies a number as positive/even, positive/odd, zero, or negative.

### Ternary Operator:

The ternary operator (`condition ? expr1 : expr2`) is a shorthand way of writing `if...else` statements for simple cases:

```javascript
let isRaining = true;
let weatherMessage = isRaining ? "Bring an umbrella" : "Enjoy the sunshine";
console.log(weatherMessage);
```

### Switch Statement:

The `switch` statement is an alternative to `if...else` for handling multiple conditions:

```javascript
let dayOfWeek = 3;

switch (dayOfWeek) {
    case 1:
        console.log("It's Monday");
        break;
    case 2:
        console.log("It's Tuesday");
        break;
    // ... additional cases
    default:
        console.log("Invalid day");
}
```

Here, the `switch` statement checks the value of `dayOfWeek` and executes the corresponding block of code.

Understanding `if...else` statements is fundamental to programming, as they enable you to control the flow of your code based on different conditions.

Contact us for software training, education or development










 

Post a Comment

0 Comments

Me