📜  javascript if else - Javascript (1)

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

JavaScript If-Else

In JavaScript, conditional statements are used to execute different actions based on different conditions. The most basic conditional statement is the if-else statement which allows you to execute one set of statements if a condition is true, and another set of statements if the condition is false.

Syntax

The basic syntax for if-else statement is:

if (condition) {
  // execute this block of code if the condition is true
} else {
  // execute this block of code if the condition is false
}

Here, condition is an expression that returns a boolean value (true or false). If the condition is true, the code within the {} block of code will be executed. If the condition is false, the code within the {} block of code following the else keyword will be executed.

Example

Let's say you want to check whether a user is an adult or a child based on their age. You can use the if-else statement to accomplish this:

const age = 20;

if (age >= 18) {
  console.log("User is an adult");
} else {
  console.log("User is a child");
}

In this example, the expression age >= 18 will return true since the value of age is 20 which is greater than or equal to 18. Therefore, the code within the {} block following the if keyword will be executed, which will print User is an adult to the console.

Multiple Conditions

You can also use multiple if-else statements to handle more than two possible outcomes:

const num = 4;

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, three possible outcomes are handled based on the value of num. If num is greater than 0, the code within the first {} block following if will be executed. If it is less than 0, the code within the second {} block following else if will be executed. If none of the above conditions are met, the code within the final {} block following else will be executed.

Conclusion

The if-else statement is a basic conditional statement in JavaScript that allows you to execute different actions based on different conditions. By using multiple if-else statements, you can handle more than two possible outcomes.