If Else in JavaScript

Branching with if and else in JavaScript is straightforward.

Here’s a basic example:

if (7 % 2 === 0) {
    console.log("7 is even");
} else {
    console.log("7 is odd");
}

You can have an if statement without an else:

if (8 % 4 === 0) {
    console.log("8 is divisible by 4");
}

Logical operators like && and || are often useful in conditions:

if (8 % 2 === 0 || 7 % 2 === 0) {
    console.log("either 8 or 7 are even");
}

In JavaScript, we can declare variables before conditionals, and these variables will be available in the current and all subsequent branches:

let num = 9;
if (num < 0) {
    console.log(num + " is negative");
} else if (num < 10) {
    console.log(num + " has 1 digit");
} else {
    console.log(num + " has multiple digits");
}

To run this JavaScript code, you can save it in a file (e.g., if-else.js) and run it using Node.js:

$ node if-else.js
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that in JavaScript, you need parentheses around conditions, and the braces are required for multi-line blocks but optional for single-line blocks.

Unlike some languages, JavaScript does have a ternary operator (?:), which can be used for simple conditional expressions:

let result = (5 > 3) ? "5 is greater" : "3 is greater";
console.log(result);  // Outputs: 5 is greater

This can be a concise alternative to a full if-else statement for simple conditions.