Javascript optimization details: Short Circuit expressions and javascript expressions
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:
What does this line of code mean? Answer:
123 |
// 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:
123 |
if (foo) // Not rigorous enough if (!!foo) // More rigorous ,!! Other types of values can be converted to the boolean type. |
You can test it:
123456789101112131415161718 |
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.
Javascript expressions
Eval is a function that dynamically executes strings.
It can be understood as var students = "{[{id: '61 ', name: 'my'}, {id: '62', name: 'hunk'}]}";
In JavaScript, why is the value of the value assignment expression itself a function and the value of this cannot be maintained?
(Object. getName = object. getName) (); // this indicates that this is the window object.
// You can add a line of code in front
Window. name = 'window name'; // the output value is Window Name;
// If you want to make the object as this, you can do this:
(Object. getName = object. getName). call (this );