This article records myself in the in-depth study of JS condition expressions in the book to understand some of the things, and record, deepen memory and convenient after review. This is an in-depth look at some of the performance optimizations and logic of the if, else and switch statements.

Strategies to improve conditional performance

As in other languages, conditional expressions in JS use if, else and switch. Because different browsers have different optimizations for flow control. Therefore, there is no difference between the two in performance, mainly according to the needs of the analysis and selection.

  • If the condition is small, chooseif elseIt’s more appropriate.
  • On the contrary, if the number of conditions is large, it is recommended to chooseswitch.

In general, if else applies to two discrete values or different range of values. If multiple discrete values are judged, switch is more appropriate.

In most cases, switch will run faster than if else.

Use if and switch appropriately

When we use conditional expressions, whether if, else or switch, we should ensure that the following three goals are basically fulfilled:

  • Accurately show the inherent and inherent logical relations of things. You can’t destroy it for the sake of structure.
  • Optimize the execution efficiency of logic. Execution efficiency is an important goal of program design, not to save trouble and arbitrary consumption of resources.
  • Simplify the code hierarchy and make the code easier to read.

Suitable for if else:

  • It has a complex logical relationship.
  • The value of the expression has linear characteristics, such as the judgment of continuous interval values.
  • The expression’s value is dynamic.
  • Test any type of data.

Suitable for Switch:

  • The value of each expression. This kind of parallel logic can be expected.
  • The values of the expression are discrete and do not have linear and discontinuous interval values.
  • The value of the expression is fixed, not dynamic.
  • The value of an expression is finite, not infinite, and in general there should be fewer expressions.
  • The value of the expression is typically integer, string type data.

For example, if you’re trying to make a different judgment about a student’s score, it would be nice to use if else, because in that case, the value of the expression is a continuous linear judgment.

JavascriptIf (socre < 60) {alert(' fail '); } else if (socre > 60 && socre <= 85) {alert(' good '); } else if (socre > 86) {alert(' good '); }

For things like gender, the switch is more appropriate.

JavascriptSwitch (sex) {case 'male ': alert(' mister '); break; Case 'female ': alert(' ladies '); break; }

Optimizing if logic

Logical order reflects the order and rigor of human thinking. Reasonable order can improve the quality of solving the problem, on the contrary, chaotic order and easy to lead to all kinds of mistakes.

People think about things that will, in time, be prepared for the most likely scenario. Another way to optimize if logic is to put the most likely conditions first and the least likely conditions second. In this way, the program will always check for all conditions in alphabetized order, and will not continue until it finds a match.

The optimization goal of if is to minimize the number of conditions judged before finding a branch. The method of IF optimization: put the most common conditions first.

JavascriptIf (I < 5) {// Execute some code} else if (I > 5 && I < 10) {// Execute some code} else {// Execute some code}

The example above, for example, is optimized only if the I value is frequently less than 5. If I is often greater than or equal to 10, then the condition body must be evaluated twice before entering the correct branch, resulting in an increase in the average time of the expression. The conditional bodies in the IF should always be arranged from the highest probability to the lowest probability to ensure the fastest theoretical speed.

If nested thinking trap

It’s a common thing to see an if statement nested inside an if statement, let’s say you have 4 adjustments, and you’ll only execute something if all of these conditions are met. In accordance with the common habit of thinking, when detecting these conditions, we often use the following structure nested:

Javascript{{if the if (a) (b) if (c) {if (d) {alert (' all conditions set up '); } else {alert(' condition d is not true '); }} else {alert(' condition c is not true '); }} else {alert(' condition b is not true '); }} else {alert(' condition a is not true '); }

In terms of the direction of thinking, there is nothing wrong with this structure. It may be more appropriate and simple to use the following if structure:

JavascriptIf (a &&b &&c &&d) {alert(' All conditions true '); }

From the previous code, the if statement is used to verify the validity of the condition one by one, and to indicate whether a condition is valid or not, so that we can track each condition. However, if you use the above if structure multiple nesting, there is another possibility: if the A condition is not true, you simply jump out of the entire nesting structure, regardless of whether the B, C, and D conditions are true. If you do this, the layered if structure makes the code too deeply nested and difficult to edit.

In order to solve the above problem, generally speaking, the method of elimination is used, that is, to exclude each condition, all the conditions are valid to perform a particular operation.

Javascriptvar t = true; if (! a) { t = false; } if (! b) { t = false; } if (! c) { t = false; } if (! d) { t = false; } if (t) {// All conditions meet requirements}

Elimination method can effectively avoid the multiple nesting problem of conditional structure mentioned above, and it is more in line with people’s thinking mode. Of course, there are some limitations, and if something goes wrong, you have to abandon the rest of the operation. If you want to prevent this kind of problem, you can design an identifier variable to track the entire operation behavior.

Small mistakes that are easy to make in the if

I don’t know if you’ve ever made the following mistake:

JavascriptIf (I = 1) {alert(I); } if (I = 1); { alert(i); }

The first is that the comparison operator === or == is sometimes miswritten as the assignment operator =. This error is often difficult to detect because it is a valid expression and does not result in a compile error.

Finally, you put the constant on the left and the variable on the right, so even if you use the = instead of ===, you’ll get an error.

Javascriptif (1 === i) {
    alert(i);
}

The second way is to add a semicolon after the if parenthesis, which changes the logic of the entire structure. We should keep in mind that differentiation is not allowed after a conditional expression, and finally prevent mistakes by putting braces on the same line as the conditional expression.

Javascriptif (i) {
    alert(i);
}

Note about writing switch

Never forget to put a break statement at the end of each case statement. You can also put a return or throw. Case statements match expression with === instead of ==.

Prevent switch penetration

In a switch statement, each condition is judged and continues to the next case condition unless the flow is explicitly interrupted. When executing a switch statement, JS computes the value of the switch condition first, then compares it with the value in each case, and executes the statement under the label if it is the same. If a jump statement is encountered during execution, the switch structure will break out. Otherwise, the execution will continue in sequence until the end of the switch statement. The default statement is executed if there is no matching case.

Javascriptswitch (a = 3) {
    case 3 - 2:
        alert(1);
    break;
    case 1 + 1:
        alert(2);
    break;
}

In the switch statement above, the case statement only indicates the starting point of the code you want to execute, but it does not indicate the end point. If you do not add a break statement to the case clause, the continuous crossing phenomenon will occur and the subsequent case clause will be ignored, which will cause the logic of the switch structure to be confused.

Finally, if there are any mistakes or questions in the article, please point out. Together with SF!