JavaScript Conditional Statements
Conditional statements in JavaScript are mainly used to execute different blocks of code based on conditions. The following is a detailed explanation and categorization of the concept of JavaScript conditional statements:
-
if statement:
- single if statement: The simplest conditional statement that determines whether to execute a particular block of code based on a condition.
- if...else statement: Execute one block of code when the condition holds, and another block of code when the condition does not hold.
- if...else if...else statements: Statements used to test a wide range of possible scenarios.
-
switch statement:
- switch...case statement: Execute different blocks of code based on different conditional values, applicable to the case of multiple conditional values.
-
ternary operator (computing):
- utilization
Condition ? Value 1 : Value 2
form, which can return different values depending on whether the condition is true or false.
- utilization
-
logical operator:
- Logic with (&&): Execute the relevant code only when all conditions are true.
- Logical or (||): Execute the relevant code whenever one of the conditions is true.
- Logical non (!): Converts true to false and false to true.
-
Falsy values and Truthy values:
- There are Falsy and Truthy concepts in JavaScript, Falsy values include false, 0, '', null, undefined and NaN, other values are considered as Truthy values.
-
Nested conditional statements:
- It is possible to nest another conditional statement inside a conditional statement to achieve more complex logical judgments.
-
Application of Conditional Statements:
- Conditional statements are often used to make decisions based on user input or program status and can enable the execution of different blocks of code on demand.
By using these conditional statements, you can execute code based on specific conditions, allowing for flexible control flow and logic. The combination of these conditional statements can help you build fully functional JavaScript applications.
if statement
In JavaScript, the simpleif
statement is used to execute a piece of code based on a specific condition. The following is a simple example that demonstrates how to use a simpleif
Statements:
let hour = 10;
if (hour < 12) {
console.log('Good morning!');
}
In the above example, ifhour
is less than 12, it will output'Good morning!'
. Ifhour
The value of does not satisfy the condition that statement will not be executed.
mereif
The statement is very suitable for situations where there is only one condition to be judged. In actual programming, you can execute different blocks of code according to different conditions to realize the flow control and logical judgment of the program.
if...else statement
In JavaScript, theif...else
statement is used to execute a block of code when the condition is true and another block of code when the condition is false. The following is an example showing how to use theif...else
Statements:
let age = 18;
if (age >= 18) {
console.log('You are of age!');
} else {
console.log('You are underage!');
}
In the above example, if theage
is greater than or equal to 18, it will output'You are of age!'
; otherwise, it outputs'You are underage!'
. This allows different prompts to be displayed depending on age.
if...else
statements are useful when you need to choose different paths to execute a block of code based on conditions. This is accomplished through the judicious use of theif...else
statements, you can implement more complex logical judgments and process controls.
if...else if...else statements
JavaScriptif...else if...else
statement allows you to select different blocks of code to execute based on multiple conditions. This kind of statement is great for scenarios where you need to consider multiple conditions. Here is an example:
let time = 14;
if (time < 12) {
console.log('Good morning!');
} else if (time < 18) {
console.log('Good afternoon!');
} else {
console.log('Good evening!');
}
In the above example, according to thetime
will output a different greeting for a different value of the If thetime
is less than 12, then the output'Good morning!'
; and iftime
Between 12 and 18, the output'Good afternoon!'
Otherwise output'Good evening!'
。
Through the rational use ofif...else if...else
statement, you can choose to execute the corresponding code block according to different situations, to achieve complex conditional judgment and program flow control.
if...else nested statements
In JavaScript, you can nested use ofif...else
statements to handle more complex conditional logic. This nesting allows you to include another conditional block within a conditional block. The following is a simple example:
let hour = 10;
let minute = 30;
if (hour < 12) {
console.log('Morning');
if (minute < 30) {
console.log('The whole point');
} else {
console.log('Half a point');
}
} else {
console.log('Afternoon or evening');
}
In the above example, different prompts are output depending on the number of hours and minutes. If the number of hours is less than 12, it will enter a nested conditional judgment and output different prompts depending on the number of minutes; otherwise, it will directly output 'afternoon or evening'.
By nesting the use ofif...else
statements, you can deal with more complex conditional cases, but you need to pay attention to keep the logic clear, to avoid too deep nested levels of code is difficult to understand.
switch statement
In JavaScript, theswitch
statement is used to select a different block of code to execute based on the value of the expression.switch
statement compares the value of the expression with a different case (case
) and executes the block of code corresponding to that situation. The following is aswitch
Example of a statement:
let day = 3;
let dayName;
switch (day) {
case 0:
dayName = 'Sunday';
break;
case 1:
dayName = 'Monday';
break;
case 2:
dayName = 'Tuesday';
break;
case 3:
dayName = 'Wednesday';
break;
case 4:
dayName = 'Thursday';
break;
case 5:
dayName = 'Friday';
break;
case 6:
dayName = 'Saturday';
break;
default:
dayName = 'Invalid date';
}
console.log('Today is' + dayName);
In the above example, according to theday
will choose different values for thecase
Execute the appropriate block of code. If theday
has a value of 3, then the output'It's Wednesday'
. Ifday
value is not between 0 and 6, then it executes thedefault
The block of code under the output'Invalid date'
。
switch
statements are typically used to test multiple possible values of an expression and execute different blocks of code based on the different values.
default keyword
In JavaScript, thedefault
Keywords are usually associated withswitch
statements together. When theswitch
The expression value of the statement does not match anycase
When it is executed, thedefault
under the code block. In this case, thedefault
Acts as an alternative to deal with situations that are not explicitly designated.
In the example you provided, if theday
is not between 0 and 6 (i.e., it is not a valid value representing the day of the week), then it will execute thedefault
The code block under thedayName
Set to 'Invalid date' to prompt the user to enter an invalid date.
default
Keywords inswitch
statement is optional, but when dealing with some unanticipated situations, it can be used as a safety mechanism to ensure that the code has an explicit way of dealing with unknown situations when faced with them.
Different application scenarios of if...else and switch
if...else
statements andswitch
statements are all used in JavaScript to make conditional judgments, but they apply to slightly different scenarios:
-
if...else
statement:- Used to deal with situations where the logic is more complex and the conditions are independent of each other.
- Can handle range-type conditional judgments, such as intervals or relationships between several different conditions.
- Can contain multiple conditions and nested conditions.
- It can handle cases where the number of conditions is uncertain or the domain of values is non-discrete.
-
switch
statement:- For performing different operations on different values of an expression.
- When multiple choices need to be made based on different values of a single variable, the
switch
can be compared toif...else
More concise. - When a large number of equivalent matches exist, the
switch
Usually more than multipleif...else
More efficient. - When successive predicate judgments occur, the
switch
Usually not applicable becauseswitch
Only equal value matching is supported.
In general, if you need to make a range judgment or if there are interactions or nested relationships between conditions, use theif...else
is more suitable; and when simple routing based on different values of a single variable is needed, theswitch
Statements.
ternary operator (computing)
The ternary operator is a conditional expression found in many programming languages. It usually consists of a conditional expression and two possible outcomes. In JavaScript, the syntax of the ternary operator is shown below:
condition ? expr1 : expr2
If the condition is true, returnexpr1
value; if the condition is false, it returns the value ofexpr2
values. The main advantage of the ternary operator is its simplicity, especially in some simple conditional cases where it can replace theif...else
statement to make the code more concise and clear.
Here is an example:
let age = 20;
let message = (age >= 18) ? 'Adults' : 'Minors';
console.log(message); // Output: 'Adults'
In this example, ifage
is greater than or equal to 18, thenmessage
is assigned as 'Adult', otherwise it is assigned as 'Minor'.
Although the ternary operator is useful in simple situations, when conditions become complex or multiple statements need to be executed, using theif...else
statements may be more readable and easier to maintain.
Follow me, don't get lost, learn and improve together!
Follow me, don't get lost, learn and improve together!