JavaScript if/else Statement

JavaScript if/else Statement

In JavaScript, the if/else statement is a conditional statement that allows us to execute different code blocks based on whether a certain condition is true or false.

Here's the basic syntax of an if/else statement:

The if statement evaluates the condition expression in parentheses. If the result of the expression is true, the code block inside the curly braces following the if statement will be executed. If the result is false, the code block inside the curly braces following the else statement will be executed.

Here's an example that uses an if/else statement to check if a number is positive or negative:

In this example, the condition expression num > 0 is evaluated. Since the value of num is 5, which is greater than 0, the code block inside the first set of curly braces is executed, and the output will be "The number is positive."

We can also use multiple if statements in a row to check for different conditions. Here's an example:

In this example, we use the else if statement to check if the value of num is less than 0. If it is, the code block inside the second set of curly braces is executed, and the output will be "The number is negative."

If the value of num is not greater than 0 and not less than 0, the code block inside the else statement is executed, and the output will be "The number is zero."

The if/else statement is an essential building block in JavaScript programming and is used in many different contexts to make decisions and execute different blocks of code based on those decisions.

Thanks for reading and learning. ❤️