The if statement is a conditional statement that is used to determine whether the condition is true. If it is true, the code within the code block is executed. Syntax: if (condition) { // Code executed when condition is true }. Where condition is an expression, and the code block is surrounded by curly braces {}. The if statement can be nested. The else statement is used to specify the code to be executed when the condition is false. The else if statement allows multiple conditions to be checked and the code block corresponding to the first condition to be true to be executed.
Usage of if statement in JS
What is if statement?
The if statement is a conditional statement used to perform different actions in JavaScript code. It is used to determine whether the condition is true. If it is true, execute the code inside the if code block.
Syntax:
<code>if (condition) { // condition 为 true 时执行的代码 }</code>
Conditions:
A condition is an expression that evaluates to true or false. It can be any valid JavaScript expression, for example:
x === 5
y > 10
z !== "hello"
Code block:
If the condition is true, then within the code block code will be executed. Code blocks are surrounded by curly braces {}
.
Nested if statements:
If statements can be nested, which means you can use another if statement within the code block of an if statement. For example:
<code>if (x > 5) { if (x > 10) { // x 大于 10 } else { // x 大于 5 但小于等于 10 } }</code>
else statement:
else statement is used to specify the code to be executed when the condition is false. The else statement immediately follows the if statement. For example:
<code>if (x > 5) { // x 大于 5 时执行的代码 } else { // x 小于等于 5 时执行的代码 }</code>
else if statement:
else The if statement allows you to check multiple conditions and execute the block of code corresponding to the first condition that is true . The else if statement immediately follows the if statement and can be used multiple times. For example:
<code>if (x > 10) { // x 大于 10 时执行的代码 } else if (x > 5) { // x 大于 5 但小于等于 10 时执行的代码 } else { // x 小于等于 5 时执行的代码 }</code>
The above is the detailed content of How to use if statement in js. For more information, please follow other related articles on the PHP Chinese website!