The short circuit expression of Javascript optimization technique is introduced in detail

  • 2020-05-19 04:14:09
  • OfStack

What is a short circuit expression?

Short circuit expressions: as operand expressions for the "&&" and "||" operators, these expressions are evaluated when the evaluation process is terminated as soon as the final result can be determined to be true or false. This is called short circuit evaluation. This is an important property of both operators.

One simple example:


foo = foo||bar;

What does this line of code mean? The answer:


// if foo Exist, the value is the same, otherwise put bar The value is assigned to foo
if(!foo)
    foo = bar;

In the logical operation of javascript, 0, "", null, false, undefined, NaN are all judged as false, and the rest as true. So foo = foo||bar; , || first calculates the first operand. If it can be converted to true, which means that foo already exists and has a value, then returns the value of the expression on the left. Otherwise, calculate the second operand bar.

In addition, even if the operator of the | | operator is not a Boolean, it can still be considered a Boolean OR operation, because it can be converted to a Boolean regardless of the type of value it returns.

Of course, it would be more rigorous to use the following approach:


if(foo)      // Not rigorous
 
if(!!foo)    // More rigorous, !! Other types of values can be converted to boolean type

You can test 1:


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 1 point can be well matched to optimize javascript project 1 to make the script run less or not run, so as to achieve the purpose of optimizing javascript. However, it is important to note that while this helps us to simplify the code, it also brings with it the disadvantage of reducing the readability of the code. So a good thing to do is to add the appropriate comments.


Related articles: