This article mainly introduces the short-circuit expression of Javascript optimization techniques. This article describes what short-circuit expressions are and provides some examples. For more information, see
What is short circuit expression?
Short-circuit expression: Used as the operand expressions of the "&" and "|" operators. When evaluating these expressions, as long as the final result is determined to be true or false, the process of evaluation is terminated, which is called short-circuit evaluation. This is an important attribute of these two operators.
A simple example:
The Code is as follows:
Foo = foo | bar;
What does this line of code mean? Answer:
The Code is as follows:
// If foo exists, the value remains unchanged; otherwise, the bar value is assigned to foo.
If (! Foo)
Foo = bar;
In the logic operation of javascript, 0, "", null, false, undefined, and NaN are both regarded as false, while others are all true. So in the above formula foo = foo | bar;, | calculate the first operation number first. If it can be converted to true, it indicates that foo already has a value, returns the value of the expression on the left. Otherwise, the second operation bar is calculated.
In addition, even if the number of | operators is not a Boolean value, it can still be considered a Boolean OR operation, because no matter what type of value it returns, it can be converted to a Boolean value.
Of course, the following practices will be more rigorous:
The Code is as follows:
If (foo) // not rigorous
If (!! Foo) // more rigorous ,!! Other types of values can be converted to the boolean type.
You can test it:
The Code is as follows:
Var foo;
Var number = 1;
Var string = "string ";
Var obj = {};
Var arr = [];
Console. log (typeof (foo); // undefined
Console. log (typeof (number); // number
Console. log (typeof (string); // string
Console. log (typeof (obj); // object
Console. log (typeof (arr); // object
Console. log (typeof (!! Foo); // boolean
Console. log (typeof (!! Number); // boolean
Console. log (typeof (!! String); // boolean
Console. log (typeof (!! Obj); // boolean
Console. log (typeof (!! Arr); // boolean
This can be a good fit for optimizing the javascript project, so that the script runs less or does not run, in order to optimize javascript. However, this helps us streamline the code and reduce the readability of the Code. Therefore, it is better to add a proper comment.