JavaScript operators (operators) and precedence

Source: Internet
Author: User
Tags bitwise bitwise operators integer division

Recently, because of the source code in the reading Underscore.js, plus the IFE before the completion of the JavaScript part of the Task2, which a large number of abbreviated sentence wording, especially like?: This trinocular operator is combined with other operators. Because the concept of operator precedence has been blurred, and is often wrapped around a circle. The following organizes the common operators and their precedence differences.

One, operator

1. Unary operators

(1) Increment decrement operator

The main difference between a++ and ++a is that when you perform a pre-increment and decrement operation, the value of the variable is changed before the statement is evaluated.

var num1 = 10;var num2 = num1++;console.log (Num1 + "  + num2);  '   ten ' var num3 = ++num1;console.log (Num1 + "  + num3);  ' 12   

(2) unary plus minus operator

This has nothing to say, because it is the existence of a unary plus and minus operator, so it is mainly used to change the ± number.

2. Bitwise operators

Understanding this bitwise operator is still quite complex and requires understanding a concept such as binary, complement, bitwise inversion, and so on, which is not much to say here, and these concepts are enough to teach a few lessons in college.

(1) Bitwise non-

~: Returns the inverse of the value, the popular is to take the inverse minus 1

(2) Bitwise AND

&: Aligns each bit of the two values, and then two values correspond to a bit of 1 o'clock to return 1, and any one is 0 and the result is 0. Here's an app that's pretty interesting:

//DOM. Contains () method compatibility notation//Execute object is the parent node function of the Parameter object Contains (Refnode, Othernode) {if (typeof refnode.contains = = "function" && (!client.engine.webkit | | Client.engine.webkit >= 522) {return refnode.contains (Othernode);} else if (typeof refnode.comparedocumentposition = = "function") {return!! (Refnode.comparedocumentposition (Othernode) & 16);} Else{var node = othernode.parentnode;do{if (node = = Refnode) {return true;} Else{node = Node.parentnode;}} while (node! = null); return false;}} Browsers that support the contains () method include IE, Firefox + +, Safari, opera, and chrome** support for the DOM Level3 Comparedocumentposition () method of browser ie9+,/***  The return values for the Firefox, Safari, Opera 9.5+, and chrome** comparedocumentposition () methods are as follows * * 1: irrelevant (the given node is not in the current document) * * 2: Before (the given node is in the DOM tree before the reference node) * * 4: After (the given node is located in the DOM tree after the reference node) * * 8: Contains (the given node is the ancestor of the reference node) * * 16: is included (the given node is the descendant of the reference node) */

In the above code else if branch, this code return!! (Refnode.comparedocumentposition (Othernode) & 16) in the Comparedocumentposition () function if the return value is less than 16, the value after the bitwise AND operation is 0, if greater than equals, The bitwise-and result is 16 (the return value in the code is 20 = 4 + 16). And here's a!! Arithmetic, because the return value requirement is true and false, two logical non-operators are required to convert the number to a Boolean value .

(3) Bitwise OR

| : Aligns each bit of the two values, and then two values correspond to a bit of 0 o'clock to return 0, and any one is 1 and the result is 1. This understanding of the bitwise and is good to understand.

(4) Bitwise XOR OR

^: Align each bit of the two numeric values, then return 0 with two values corresponding to the digits, and return 1 for different results. This is understood by bitwise and/or by bit or just fine.

(5) Shift Left (<<)/Signed Right Shift (>>)/Unsigned Right shift (>>>)

This said really I use less, here does not unfold the description, has the interest can check oneself.

3. Boolean operators

(1) Logical non-

! : It is worth noting that the logical non-operator first converts its operand to a Boolean value and then deserializes it . One of the most important applications is mentioned above: using two logical non-operators, in effect, simulates the behavior of a Boolean () transformation function .

(2) Logic and

&&: The logic and Operation Boolean value is not more than the case, as long as there is false return false, all true returns True. The main consideration here is the case where the logic and operators are applied to other types of operands:

    • If the first operand is an object, a second operand is returned;
    • If the second operand is an object, the object is returned only if the first operand evaluates to true;
    • If two operands are objects, a second operand is returned;
    • If one of the operands is null/nan/undefined, the null/nan/undefined is returned;

It is also worth noting that the logical and short-circuit operations , the first operand return value is false, no longer evaluates the second operand (note, here is the evaluation).

(3) Logical non-

|| : And logic is, after all, a brother, the Boolean value of arithmetic is that it returns true if it is true, and all false returns FALSE. Take a closer look at the case where the logical non-operator is applied to other types of operands:

    • If the first operand is an object, the first operand is returned;
    • If the evaluation result of the first operand is false, the second operand is returned;
    • If the two operands are objects, the first operand is returned;
    • If the two operands are null/nan/undefined, the null/nan/undefined is returned;

Logically and similarly, logic is not a short- circuit operation , there is also an interesting application, in the previous writing JQuery plug-ins, when passing the parameter options to the initialization function, in order to avoid the assignment of undefined or null, This code is often added to the process of initializing parameters:

var _options = Options | | {};

  the preceding options contain the value assigned to the _options, and the next {} empty object is responsible for providing the fallback value in case the previous options do not contain a valid value. because this code is often followed by the expansion of user-defined parameters and default parameters, it is not possible to pass a null value.

The application of logic and logic not in code writing is often very common, especially if the rules of an object that are not Boolean-valued are important.

  By virtue of their own level in the application to write or use is not familiar with, or to continue to reconstruct their original writing code, not far to summarize the reflection.

4. Multiplicative operator/additive operator

Here is the main +-*/% of these five operators of the operation characteristics, relative to the basic mathematical operations, as well as string concatenation, in my use of the process, some other more Geek usage I did not how to deal with. Here are some noteworthy areas:

    • JavaScript inside/arithmetic is not the same as before I contact with the integer division of the operation effect, is the common divide operation, except for a long string of decimals;
    • Because JavaScript is based on the IEEE754 value of the floating-point number calculation, so there will be 0.1 + 0.2≠0.3 case, so as far as possible to use conversion to integer arithmetic; explain to me.

Other numeric operations such as NaN and Infinity are not within the scope of the operators discussed here.

5. Relational operators

> < >= <=: There are some rare tricks in this comparison. In addition to our common numerical comparisons, there are some more expanded knowledge:

    • When comparing two strings, the actual comparison is the character encoding value for each character in the corresponding position in the two string . This involves the concept of character set and character encoding, which is not discussed here. Because the character encoding of the uppercase letters is all less than the character encoding of the lowercase letters, the following situation is displayed:
      var result = "Bob" < "Alin";    True
    • There is also a > <= comparison of two identical operands with the same result. According to the rule, when any operand is compared to NaN, the result is false , because the letter cannot be converted to a reasonable value, so the following is the case:
      var result1 = ' a ' > 1;    Falsevar result2 = ' a ' <= 1;     False

6. Equality operators

The main difference here is (not) equality and (not) congruent. The equality operator (= =) has a type conversion operation, where the main application is to return true if the comparison of a pure numeric string and a number similar to "5" = = 5 . It is worth noting that the null = = undefined return is true. and the congruent (= = =) requirement is not only two operands of the same value, but also requires the same numeric type. So both of the above cases return false in the case of equality. In actual code writing, it is still recommended to have congruent and non-congruent operators.

7. Conditional operators

Variable = boolean_expression? True_value:false_value;

The assignment of the variable variable is determined based on the result of evaluating the boolean_expression value. If the evaluation result is true, the variable is assigned a value of true_value, otherwise it is false_value. In conjunction with the other operators, the conditional (trinocular) operator can play out its flexibility and efficiency.

8. Assignment operators

=: Assigns the value on the right to the variable on the left. Similar to *=,/=,%=, + =,-=, <<=, >>=, >>>=. The main purpose of using these operators is to simplify assignment operations without any performance gains.

9. Comma operator

You can use the comma operator to perform multiple operations in a single statement, such as common assignment statements:

var num1 = 1, num2 = 2, num3 = 3;

In addition, the comma operator can also be used to assign values. When assigning a value, the comma operator always returns the last item of the expression, such as the following example:

var num = (1, 2, 3, 4, 5, 0);    The value of NUM is 0

And this interview question:

var num = (key = 12, 0); The value of NUM is 0

Ten. typeof operators

This operator is primarily used to detect the data type of a given variable, and the return value is as follows:

    • "Undefined"-if this value is undefined;
    • "Boolean"-if this value is a Boolean value;
    • "String"-if this value is a string;
    • "Number"-if the value is numeric;
    • "Object"-if this value is an object or null;
    • "Function"-if this value is a function;

This explains why typeof null returns "Object" and also explains why NULL = = undefined returns true: thenull value itself represents an empty object pointer , and using typeof returns "Object In fact,undefined is derived from a null value , so the equality test for both is to return true. Thus, it is not necessary to set the value of a variable to undefined, but as long as the variable intended to hold the object does not have a true save object, it should be explicitly saved with a null value.

Second, operator precedence

The following table lists the JavaScript operators from highest to lowest precedence, and operators with the same precedence are evaluated in left-to-right order:

Operator Describe
. [] () Property access, array subscripts, function calls, and expression grouping
++ -- ~ ! +-delete new typeof void Unary operators, return data types, object creation
* / % Multiplication, division, modulo
+ - addition, subtraction
>> << >>> Shift Operations
< <= > >= instanceof Less than (equals), greater than (equals),
== != === !== (not) equals, (not) congruent
& Bitwise-AND
^ Bitwise XOR OR
| Bitwise OR
&& Logic and
|| Logical OR
?: Condition (trinocular) operator
= += Assignment, Operation assignment
, Multiple evaluation (comma operator)

The situation in this case is the following:

return parts[0] && result[0]? Filterparents (parts, result): result;

It is determined that the parts array does not contain data objects, so I fell into a dead end, always thought that the return is undefined, and finally think of the problem that might be the operator precedence, because in the conditional operator to determine the condition directly return undefined, converted to false, The resulting value is then returned as the result value. It is important to note the precedence of operators in the future.

JavaScript operators (operators) and precedence

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.