How to use conditional statements (if-else) in JavaScript?

In JavaScript, conditional statements are used to perform different actions based on different conditions. The most common type of conditional statement is the if-else statement.

Here's the general syntax of an if-else statement:

if (condition) { // do something if condition is true } else { // do something if condition is false }

Here's an example of using if-else statement in JavaScript:

let num = 10; if (num > 0) { console.log("Number is positive"); } else { console.log("Number is negative"); }

In this example, the condition num > 0 is checked. If the condition is true, the code inside the if block (console.log("Number is positive")) is executed. If the condition is false, the code inside the else block (console.log("Number is negative")) is executed.

You can also have multiple conditions by combining multiple if-else statements or by using the else if statement. Here's an example:

let num = -5; if (num > 0) { console.log("Number is positive"); } else if (num < 0) { console.log("Number is negative"); } else { console.log("Number is zero"); }

In this example, there are three conditions: num > 0, num < 0, and num === 0. The code inside the first block that matches the condition is executed.

You can also nest if-else statements within each other to create more complex conditions.

Remember to use parentheses to define conditions, and use curly braces to define blocks of code for each condition.