Home >Web Front-end >JS Tutorial >JavaScript If...Else Statement_Basics

JavaScript If...Else Statement_Basics

WBOY
WBOYOriginal
2016-05-16 19:15:441189browse

Conditional declarations in JavaScript are used to complete behaviors under different conditions.
Conditional Statement
When you write code, you often need to complete different behaviors based on different conditions. You can use conditional statements in your code to accomplish this task.
In JavaScript, we can use the following conditional statements:
if statement
Execute code when a specified condition is true.
if...else statement
Execute code when the specified condition is true, and execute other code when the condition is not true.
if...else if....else statement
Use this statement to choose to execute one of several blocks of code.
switch statement
Use this statement to choose to execute one of several blocks of code. If Statement
You can use this statement if you want the code to be executed when the specified condition is true.
Syntax:

Copy code The code is as follows:

if (condition)
{
Execute code when the condition is true
}

Note: Please use lowercase letters. Using uppercase IF is an error!
Example 1

[Ctrl A Select all Note: If you need to introduce external Js, you need to refresh to execute
]

Example 2

[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]

Note: Please use double etc. (==) to compare variables!
Note: There is no else in the syntax. The code will only be executed when the condition is true.
If...else Statement
If you want to execute a piece of code when the condition is true, and execute another piece of code when the condition is not true, you can use the if....else statement.
Syntax:
if (condition)
{
Execute this code when the condition is true
}
else
{
Execute this code when the condition is not true
}
Instance
[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]

If...else if ...else statement
When you need to select one of multiple sets of codes to run, please use if....else if...else statement. Syntax: Copy code

The code is as follows:


if (Condition 1)
{
Execute code when condition 1 is true
}
else if (condition 2)
{
Execute code when condition 2 is true
}
else
{
Execute code when neither condition 1 nor condition 2 is true
}

[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute ]
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn