What is a short-circuit expression?
Short-circuit expression: as "&&" and "| |" Operator's operand expression, when evaluated, as long as the final result can be determined to be true or FALSE, the evaluation process terminates, which is called short-circuit evaluation. This is an important attribute of these two operators.
One of the simplest examples:
Copy Code code as follows:
What does this line of code mean? Answer:
Copy Code code as follows:
If foo exists, the value is unchanged, otherwise the value of bar is assigned to Foo
if (!foo)
foo = bar;
In the logical operation of JavaScript, 0, "", null, false, undefined, and Nan are all judged false, while others are true. So in the upper-style foo = foo| | Bar; Medium, | | Calculates the first operand, if it can be converted to true, meaning that Foo already has a value, returns the value of the expression on the left, or the second operand bar.
In addition, even if | | The operand of an operator is not a Boolean value and can still be treated as a Boolean or operation because, regardless of the type of value it returns, it can be converted to a Boolean value.
Of course, the use of the following approach will be more rigorous:
Copy Code code as follows:
if (foo)//Not rigorous
if (!! FOO)//More rigorous,!! Other types of values can be converted to a Boolean type
Can test:
Copy Code code 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 well met by optimizing JavaScript Engineering as mentioned in the article, making scripts less or not running to optimize JavaScript for the purpose. Note, however, that this writing helps us streamline the code while also bringing down the drawbacks of code readability. So better to do is to add the appropriate annotation.