JavaScript Conditional Expressions Deep learning

Source: Internet
Author: User
Tags case statement expression

JS conditional expression and other languages, have adopted if else and switch these two kinds. Because different browsers have different optimizations for process control. So there is no difference in performance between the two, mainly based on the needs of analysis and selection.

If the condition is small, choose if else is more appropriate.

Conversely, if the number of conditions is large, it is recommended to use switch.

In general, if else is applicable to two discrete values or different value ranges. If you are judging multiple discrete values, it is more appropriate to use a switch.

In most cases, the switch runs more quickly than if else.

Proper use of IF and switch

When we use a conditional expression, whether if else or switch, you should ensure that the following 3 goals are basically implemented:

To express the intrinsic and intrinsic logical relationship of things accurately. Cannot be destroyed for the sake of structure.

Optimize the execution efficiency of the logic. Execution efficiency is an important goal of program design, and it can not consume resources freely for the sake of convenience.

Simplify the structure of your code to make your code easier to read.

A condition suitable for using if else:

Has a complex logical relationship.

The value of an expression has a linear character, such as a continuous interval value.

The value of an expression is dynamic.

Test any type of data.

Suitable for use with switch:

The value of the expression for each sentence. This is a parallel logical relationship that can be expected.

The value of an expression is discrete and does not have a linear discontinuous interval value.

The value of the expression is fixed, not dynamically changed.

The value of an expression is finite, not infinite, and the expression should generally be less.

The value of an expression is typically an integer, a string-type data.

For example, the student's score is judged differently, and it is appropriate to use the if else at this time, because in this case the value of the expression is a continuous linear judgment.

if (Socre < 60) {

Alert (' fail ');

else if (Socre > && socre <= 85) {

Alert (' good ');

else if (Socre > 86) {

Alert (' excellent ');

}

And the use of the switch is more appropriate to determine gender.

Switch (Sex) {

Case ' Male ':

Alert (' Mr. ');

Break

Case ' female ':

Alert (' lady ');

Break

}

Optimizing If logic

The logical order embodies the orderliness and rigor of the human mind. Reasonable order can improve the quality of problem solving, instead, the Order of chaos and the occurrence of all kinds of errors easily lead to.

When people think about things, they will be prepared for what is most likely to happen. If you want to optimize if logic, you can also think of the most likely conditions in the front, the most unlikely conditions in the back, so that the program is always executed in accordance with the name of the order of the first detection of all the conditions, know that the conditions will stop to find matching to continue detection.

The optimization goal of if: Minimize the number of conditional bodies that are judged before the branch is found. If optimization method: Put the most common conditions in the first place.

if (I < 5) {

Execute some code

else if (i > 5 && i < 10) {

Execute some code

} else {

Execute some code

}

For example, the above example is optimized only if the I value is often less than 5. If the I value is often greater than or equal to 10, then before entering the correct branch, it must be two times the operator, resulting in an increase in the average operation time of the expression. The conditional body in the if should always be arranged according to the maximum probability to the lowest probability to ensure the theoretical speed is the fastest.

The thought trap of if nesting

Nested an If statement inside an if statement is a common thing to see, assuming that there are 4 price adjustment you, only when these conditions are satisfied with the requirements, will carry out certain things. Following the common people's thinking habits, in the detection of these conditions, often follow this structural nesting:

if (a) {

if (b) {

if (c) {

if (d) {

Alert (' All conditions set up ');

} else {

Alert (' Condition D not established ');

}

} else {

Alert (' Condition c not established ');

}

} else {

Alert (' Condition b not established ');

}

} else {

Alert (' Condition A is not established ');

}

From the direction of thinking, this structure is not wrong, the use of the following if structure to express may be more appropriate and simple:

if (a && b && C && d) {

Alert (' All conditions set up ');

}

From the code just now, use the IF statement to verify the legality of the condition one at a time, and to be prompted about whether a condition is legitimate, so that we can track every condition. However, if you use the above if structure multiple nesting, there will be another possibility: a condition if not set up, will jump straight out of the entire nesting structure, will not go to the tube b,c,d condition is established. If you do this, the layer-wrapped if structure makes the code too deep and difficult to edit.

In order to solve the above problems, generally use the exclusion method, that is, the exclusion of each condition, the conditions are all set up in the implementation of specific operations.

var t = true;

if (!a) {

T = false;

}

if (!b) {

T = false;

}

if (!c) {

T = false;

}

if (!d) {

T = false;

}

if (t) {

Conditions all meet the requirements

}

The elimination method effectively avoids the multiple nesting problem of the conditional structure mentioned above, and it is more consistent with the human thinking mode. Of course, there are some limitations, in the event of an error, it is necessary to give up the operation behind. If you want to prevent this type of problem from happening, you can design a variable to track the entire action.

Easy to make a small mistake in if

I don't know if we have any wood. The following error has been made:

First Kind

if (i = 1) {

alert (i);

}

Second Kind

if (i = 1);

{

alert (i);

}

The first is that sometimes the comparison operation = = or = = Fu is written as an assignment operator =. And this kind of error is generally difficult to find, because it is a legitimate expression, does not cause a compilation error.

Finally put the constant on the left, the variable on the right, so that if you take = as a = = To use also will be an error.

if (1 = = i) {

alert (i);

}

The second is that a semicolon is appended to the parentheses of the If, which causes the logic of the entire structure to change. We should keep in mind that conditional expressions do not allow you to add differentiation, and then prevent mistakes by writing braces and conditional expressions on one line.

if (i) {

alert (i);

}

Write the switch to pay attention to the place

Never forget to put a break statement behind each case statement. You can also put a return or throw.

Prevent switch running through

In a switch statement, the next case condition is run through each condition, unless the process is explicitly interrupted. In executing a switch statement, JS calculates the value of the switch condition and then uses the value to compare to the value in each case, and if the same executes the statement under the label. If you encounter a jump statement at execution time, you will jump out of the switch structure, or you will follow the sequence and know the end of the switch statement. If there is no matching case, the default statement is executed.

Switch (A = 3) {

Case 3-2:

Alert (1);

Break

Case 1 + 1:

Alert (2);

Break

}

In the switch statement above, the case statement simply indicates the starting point of the code you want to execute, does not specify the end point, and if you do not add a break statement to the case clause, a sequential penetration occurs, which ignores the latter clause. This creates a logical confusion of the switch structure.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.