Document directory
- Level 1 Understanding
- Level 2 Understanding
- Level 3
- Knowledge Extension
Operators can be understood at three different levels.
Level 1 Understanding
When the operands are boolean values, "&" performs the Boolean AND (AND) operations on the two values.
Copy codeThe Code is as follows: x = 0 & y = 0 // true is returned only when x and y are both 0.
The priority of Relational operators is higher than that.
Level 2 Understanding
"&" Boolean AND (AND) operations can be performed on the true AND false values. (False, null, undefined, 0, NaN, and ""). In JavaScript, where boolean values are to be used, expressions and statements treat them as true values or false values. Therefore, "&" does not always return true or false values.
Copy codeThe Code is as follows: null & true // => null: The left operand is a false value and returns it. The entire expression is a false value.
True & (5-3) // => 2: The left operand is true. Calculate the right operand and return the result to the third layer.
When an operator returns a true or false value, two operations are performed based on the value of the left operand: The operator first calculates the value of the left operand. If the calculation result is a false value, therefore, the result of the entire expression must be a false value. At this time, the "&" Operation simply returns the value of the left operand instead of the right operand. If the left operand is a true value, "&" calculates the value of the right operand and returns it as the calculation result of the entire expression.
Copy codeThe Code is as follows: var o = {x: 1 };
Var p = null;
O & o. x; // => 1 o is the true value and returns the value of o. x.
P & p. y; // => null: p is a false value. Return it instead of p. y.
"&" Is sometimes called a "Short Circuit". We will see that many codes use this feature to execute code conditionally. For example, the following two lines of code are equivalent:
Copy codeThe Code is as follows: if (a = B) stop ();
(A = B) & stop (); // extends the equivalent knowledge of the preceding statement
The operators "|" and "&" also have complex behaviors.
Used to select the first true value expression from a set of alternative expressions:
Copy codeThe Code is as follows: // first check whether a is the true value. If yes, return a. Otherwise, process B in the same way as.
// If B is the true value, return B; otherwise, return 5.
Var max = a | B | 5;
This method can be used in functions to provide default values for parameters:
Copy codeThe Code is as follows: function copy (o, p ){
P = p | {}; // if the object is not passed to parameter p, the newly created object is used.
//...
}
Operator priority
For operators with the same priority, the operation order is determined by the combination direction.
Note :! > Arithmetic Operators> Relational operators >&>||> value assignment operators