What is a short-circuit expression?
short-circuit expression: as "&&" and "| |" Operator's operand expression, which is evaluated as long as the final result can be determined to be true or FALSE, the evaluation process terminates, which is called a short-circuit evaluation. This is an important property of these two operators.
One of the simplest examples:
Foo = foo| | Bar
What does this line of code mean? Answer:
If foo exists, the value is not changed, otherwise the value of bar is assigned to Fooif (!foo) foo = bar;
In JavaScript logic operations, 0, "", null, false, undefined, and Nan are all judged to be false, while others are true. So foo = foo| in the upper style | Bar, middle, | | Calculates the first operand first, if it can be converted to true, which means that Foo already has a value, then returns the value of the expression on the left, otherwise calculates the second operand bar.
In addition, even if | | Operator is not a Boolean value, you can still treat it as a Boolean or operation because it can be converted to a Boolean value regardless of the type of value it returns.
Of course, the use of the following practices will be more rigorous:
if (foo) //Not rigorous if (!! Foo) //More rigorous,!! Other types of values can be converted to Boolean types
You can test it:
var foo; var number = 1;var String = "string"; var obj = {};var arr = [];console.log (typeof (foo)); Undefinedconsole.log (typeof (number)); Numberconsole.log (typeof (String)); Stringconsole.log (typeof (obj)); Object Console.log (typeof (arr)); Objectconsole.log (typeof (!! foo)); Booleanconsole.log (typeof (!! number)); Booleanconsole.log (typeof (!! string)); Booleanconsole.log (typeof (!! obj)); Booleanconsole.log (typeof (!! ARR)); Boolean
The use of this can be well-tuned, as mentioned in the article optimizing JavaScript engineering , so that scripts run less or do not run to optimize JavaScript. However, it is important to note that this helps us to streamline the code, but also brings the disadvantage of reducing the readability of the code. So better to do is add is appropriate comment.
More optimization methods can see my previous blog: Front-end engineering optimization: JavaScript optimization summary .
JavaScript optimization Details: short-circuit expression