gogoWebsite

14 Learning JavaScript: Conditional Statements

Updated to 3 hours ago

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:

  1. 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.
  2. switch statement

    • switch...case statement: Execute different blocks of code based on different conditional values, applicable to the case of multiple conditional values.
  3. ternary operator (computing)

    • utilizationCondition ? Value 1 : Value 2 form, which can return different values depending on whether the condition is true or false.
  4. 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.
  5. 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.
  6. Nested conditional statements

    • It is possible to nest another conditional statement inside a conditional statement to achieve more complex logical judgments.
  7. 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...elsestatement 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...elseStatements:

let age = 18;

if (age >= 18) {
    console.log('You are of age!');
} else {
    console.log('You are underage!');
}

In the above example, if theageis 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...elsestatements 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...elsestatements, you can implement more complex logical judgments and process controls.

if...else if...else statements

JavaScriptif...else if...elsestatement 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 thetimewill output a different greeting for a different value of the If thetimeis less than 12, then the output'Good morning!'; and iftimeBetween 12 and 18, the output'Good afternoon!'Otherwise output'Good evening!'

Through the rational use ofif...else if...elsestatement, 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...elsestatements 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...elsestatements, 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, theswitchstatement is used to select a different block of code to execute based on the value of the expression.switchstatement compares the value of the expression with a different case (case) and executes the block of code corresponding to that situation. The following is aswitchExample 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 thedaywill choose different values for thecaseExecute the appropriate block of code. If thedayhas a value of 3, then the output'It's Wednesday'. Ifdayvalue is not between 0 and 6, then it executes thedefaultThe block of code under the output'Invalid date'

switchstatements 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, thedefaultKeywords are usually associated withswitchstatements together. When theswitchThe expression value of the statement does not match anycaseWhen it is executed, thedefaultunder the code block. In this case, thedefaultActs as an alternative to deal with situations that are not explicitly designated.

In the example you provided, if thedayis not between 0 and 6 (i.e., it is not a valid value representing the day of the week), then it will execute thedefaultThe code block under thedayNameSet to 'Invalid date' to prompt the user to enter an invalid date.

defaultKeywords inswitchstatement 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...elsestatements andswitchstatements are all used in JavaScript to make conditional judgments, but they apply to slightly different scenarios:

  1. if...elsestatement

    • 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.
  2. switchstatement

    • 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, theswitchcan be compared toif...elseMore concise.
    • When a large number of equivalent matches exist, theswitchUsually more than multipleif...elseMore efficient.
    • When successive predicate judgments occur, theswitchUsually not applicable becauseswitchOnly 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...elseis more suitable; and when simple routing based on different values of a single variable is needed, theswitchStatements.

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, returnexpr1value; if the condition is false, it returns the value ofexpr2values. The main advantage of the ternary operator is its simplicity, especially in some simple conditional cases where it can replace theif...elsestatement 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, ifageis greater than or equal to 18, thenmessageis 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...elsestatements 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!

在这里插入图片描述