What is a short circuit expression?
Short-circuit expression: As the operand expression of the "&&" and "||" operators, when these expressions are evaluated, as long as the final result can be determined to be true or false, the evaluation process will be Termination, this is called short-circuit evaluation. This is an important property of these two operators.
The simplest example:
What does this line of code mean? Answer:
In the logical operation of JavaScript, 0, "", null, false, undefined, and NaN will all be judged as false, while everything else will be judged as true. So in the above formula foo = foo||bar;, || first calculates the first operand. If it can be converted to true, which means that foo already has a value, then the value of the expression on the left is returned, otherwise Calculate the second operand bar.
In addition, even if the operand of the || operator is not a Boolean value, it can still be regarded as a Boolean OR operation, because no matter what type of value it returns, it can be converted to a Boolean value.
Of course, it would be more rigorous to use the following approach:
You can test it:
Using this can be very consistent with what is mentioned in the article Optimizing JavaScript Projects, so that the script runs less or not at all to achieve the purpose of optimizing JavaScript. However, it should be noted that while writing this way helps us streamline the code, it also brings the disadvantage of reducing the readability of the code. So a better thing to do is to add comments that are appropriate.