📜  if javascript(1)

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

If Javascript

if is a conditional statement in JavaScript used to execute a block of code only if a particular condition is true. The if statement evaluates a condition in parentheses and executes the subsequent block of code if the condition is true. If the condition is false, then the block of code inside the if statement is skipped.

Syntax

The if statement has the following syntax:

if (condition) {
  // code to execute if condition is true
}
Example
// Check if the given number is even or odd
let num = 10;

if (num % 2 === 0) {
  console.log(num + " is even");
} else {
  console.log(num + " is odd");
}
// Output: 10 is even

In the above example, the % operator is used to check if the number is even or odd. If the remainder of the number divided by 2 is 0, then the number is even, and if it is 1, then the number is odd.

Multiple conditions

You can also use logical operators to combine multiple conditions in an if statement. The logical operators are && (AND), || (OR), and ! (NOT).

// Check if the given number is between 1 and 10
let num = 5;

if (num > 1 && num < 10) {
  console.log(num + " is between 1 and 10");
} else {
  console.log(num + " is not between 1 and 10");
}
// Output: 5 is between 1 and 10

In the above example, the && operator is used to check if the number is greater than 1 and less than 10.

Conclusion

The if statement is a fundamental building block in JavaScript programming and is used extensively in writing programs. By using the if statement, you can make your program more dynamic and responsive to user input.