📜  js if else - Javascript (1)

📅  最后修改于: 2023-12-03 15:16:58.792000             🧑  作者: Mango

JavaScript If-Else Statements

JavaScript logo

The if-else statement is one of the fundamental control structures in JavaScript. It allows you to specify different actions to be performed based on a certain condition. This enables your program to make decisions and execute different code blocks accordingly.

Syntax

The syntax for the if-else statement in JavaScript is as follows:

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

The condition is an expression that evaluates to either true or false. If the condition is true, the code block inside the if statement will be executed. Otherwise, the code block inside the else statement will be executed.

Example

Let's consider an example where we want to check if a given number is positive or negative:

let number = -5;

if (number > 0) {
  console.log("The number is positive.");
} else {
  console.log("The number is negative.");
}

In this example, the condition number > 0 is evaluated. If the number is greater than 0, the message "The number is positive." is printed to the console. Otherwise, the message "The number is negative." is printed.

Multiple Conditions with else if

You can also have multiple conditions using the else if statement. This allows you to add additional code blocks to be executed based on different conditions. The else if statement comes after the initial if statement and before the else statement.

let number = 0;

if (number > 0) {
  console.log("The number is positive.");
} else if (number < 0) {
  console.log("The number is negative.");
} else {
  console.log("The number is zero.");
}

In this example, if the number is greater than 0, the message "The number is positive." is printed. If the number is less than 0, the message "The number is negative." is printed. If none of these conditions are met, the message "The number is zero." is printed.

Conclusion

The if-else statement is a crucial part of JavaScript programming. It allows you to control the flow of your code based on conditions, giving your program the ability to make decisions. Understanding how to use if-else statements is essential for writing flexible and interactive JavaScript programs.