JavaScript advanced programming (version 3rd) learning notes 4js operators and operators _ basic knowledge

Source: Internet
Author: User
If the data type is the brick of the programming language, the operators and operators are the lime and cement of the programming language. It is a mixture of values of various data types, so that the data value is no longer just an isolated value, but there is a dynamic spirit in ECMAScript, there are a lot of operators and operators, in this article, we will sort the data by the usual categories. However, before sorting the data, Let's explain the following:

1. Although the title is an Operator and an Operator, it seems to me that there is not much need to be strictly differentiated. In English, it seems to be represented by an Operator, so I may mix them later. Even some operators that do not fall into the category of operators and operators are also organized here as long as I feel necessary.

2. You do not need to keep in mind the priority of operators-I believe you know the simplest "multiplication, division, and addition and subtraction". If you are not sure about anything else, add parentheses. In ECMAScript, operations with the same priority are performed from left to right.

3. For some operators commonly used in programming languages, such as common Arithmetic Operators (+-*/), I will simply list them and not expand them. However, please note that, it doesn't mean that these are not important. On the contrary, these general operators are even in a very basic position, but I think you should be familiar with them early, and there is no need to spend time here to emphasize them.

4. What are the important points here? It is some special operators in ECMAScript, or some places that I think are worth the time to emphasize.

Operators and operators

Category Operator Description Description
Unary operator ++ Auto-increment 1

1. There are two types of auto-increment (subtraction): Pre-increment and post-increment. Pre-increment (subtraction) is used for other operations, and post-increment is used for other operations before auto-increment (subtraction ).

2. In ES, auto-increment (subtraction) applies not only to integers, but also to any value. For values not of the Number type, they are implicitly converted to Number according to the rules in the previous article, then, auto-increment (subtract) is used to change the variable type to the Number type.

-- Auto-minus 1
+ Mona1 Addition The main application of mona1 addition is to convert the operands to the Number type, which is equivalent to calling Number () conversion.
- RMB reduction The unary Subtraction is based on The unary addition and returns the opposite number.
Arithmetic Operators + Add

1. Apart from adding (+), if the operand is not of the Number type, the system will automatically call Number () to convert it to the Number type for calculation.

2. For addition and subtraction (+-), except as arithmetic operators. It can also be used as an unary operator (see above ). Of course, because of the overload of the plus sign (+) in the string operation, it can also be used to connect any value (the string). This is why the addition of (+) in the 1st point is required ), when it contains a non-Number value, it converts all operands into strings.

3. Unlike the General C language, in ES, Division (/) and modulo (%) do not distinguish between integers and floating-point numbers, such as 5/2 = 2.5 instead of 2, 5.3% 3 = 2.3 instead of 2.

4. Any operation. If the operand contains NaN, the result is NaN. However, if the result is not NaN, there must be an operand NaN. For example, 0/0 also returns NaN.

5. There are many rules for operations with Infinity. I will not list them here. You can refer to the original book or test them yourself.

- Subtraction
* Multiplication
/ Division
% Modulo
Logical operators

(Boolean operator)

! Non-logical

First, convert the operand to a Boolean value, and then return the inverse value. Double Non !! Converts a value to a corresponding Boolean value.

&& Logic and

1. If the corresponding Boolean values of the two operands are true, true is returned.

2. Short Circuit: when the corresponding Boolean value of the first operand is false, false is directly returned and the second operand is not calculated. This is often used to determine whether a variable (attribute) is defined, for example:
If (object & object. name & object. name = 'linjisong '){}
Here, we will first determine whether the object exists. If the object does not exist, the object. name will not be parsed to prevent the error from occurring. Similarly, only the object. name exists can be compared.

| Logic or

1. if at least one Boolean value of the two operands is true, true is returned.

2. Short-circuit: when the corresponding Boolean value of the first operand is true, true is returned directly without calculating the second operand.

3. Logic or, in addition to general judgment, is often used to provide default values, such:

Function Fn (obj ){
Obj = obj | {};

If Fn is called and obj is not passed in, the obj is automatically assigned undefined, and an empty object {} is assigned to obj because the corresponding Boolean value of undefined is false, if obj is passed in the call, because the Boolean value of any object is true, the subsequent {} will not be obtained, thus giving obj a default value.

This method is also applied to multiple relatively independent files in a large JS Library:
// JsLib
Var jsLib;
// File1
(Function (jsLib ){
JsLib = jsLib || {};
}) (JsLib );

// File2
(Function (jsLib ){
JsLib = jsLib || {};
}) (JsLib );

In this way, no matter which file is loaded first, it will determine whether jsLib has been defined. If it is not defined, a default value is provided. In this way, the loading sequence can be ignored for relatively independent modules.

Relational operators

(Comparison operator)

< Less

1. If one of the operands is a value of the Number or Boolean type, convert the two operands to a value of the Number type (if needed) for numerical comparison.

2. compare strings to compare character encoding values one by one.

3. When the operator is an object, call valueOf () (if not, call toString () and compare the result according to the above rules.

4. If any number is compared with NaN, false is returned.

<= Less than or equal
> Greater
> = Greater than or equal
= Equal

1. Equal and unequal (= ,! =) During comparison, implicit type conversion is required.

2. Full and incomplete (=== ,! =) During comparison, the type will not be converted. If the types are inconsistent, it is directly! =.

3. Combined with 1 and 2, we can know that a = B must have a = B, and! = B, there must be! = B.

! = Not Supported
=== Full
! = Incomplete
Value assignment operator = Assignment
Compound arithmetic value assignment operator Arithmetic Operators plus = Corresponding Arithmetic Operators include + =,-=, * =,/=, and % =
Compound bitwise assignment operator Add = To the bitwise Operator Corresponding bitwise operator, ~ =, <=, <=, >=, >>>> =
Bitwise Operator ~ Non-bitwise Bitwise inversion, that is, back code
& Bitwise AND Bitwise alignment and bitwise operation. Only one of the two bitwise operations returns 1. Otherwise, the bitwise operation returns 0 and returns the result of all bitwise operations.
| By bit or Bitwise alignment and bitwise operation. 0 is returned only when both bitwise values are 0. Otherwise, 1 is returned for this bitwise, and all bitwise operation results are returned in combination.
^ Bitwise OR Bitwise alignment and bitwise operation. If two bitwise operations are not the same, 1 is returned. Otherwise, 0 is returned, and all bitwise operation results are returned.
< Move left Shifts the binary number to the left without changing the symbol bit.
> Shifts right with a symbol Shifts the binary number to the right, and fills the position with a high position.
>>> Unsigned right shift Shifts the binary number to the right and directly shifts the right. For positive numbers, the result is the same as>. For negative numbers, the binary complement code of negative numbers is treated as the binary code of positive numbers.
String Operators + String connection Equivalent to the concat () function, all operands are first converted to strings and then connected. Note: Once a string is created, it will not change. When you execute a string connection, there will be an intermediate connection and destruction process in the background. This is also the reason why the old browser runs slowly in a large number of string connection operations.
+ = String concatenation A + = B, equivalent to a = a + B.
Object Operators . Attribute accessors Simple Object attribute accessors.
[] Attribute or (class) array access [] Allows you to access attributes whose names are variables or contain special characters.
New Call the constructor to create an object Returns a newly created object. this inside the constructor is directed to this newly created object.
Delete Deletion of variables and attributes Delete attributes (variables can be viewed as global objects or an attribute of the execution environment ).
Void Return undefined.
In Determining attributes Object or prototype link.
Instanceof Prototype judgment Compares whether an object in the same context is a prototype of another object.
Other operators ? : Conditional Operators Syntax; var value = exp? TrueExp: falseExp. Equivalent to var value; if (exp) {value = trueExp;} else {value = falseExp ;}
, Comma Operator It is mainly used to declare multiple variables, which is also a popular practice of many JS libraries. For example, var num1 = 1, num2 = 2, num3 = 3;
() Grouping operators

Main purpose:

1. Use the comma operator to assign values. For example, var num = (, 0); here the final value of num is 0.

2. convert to an expression. For example, eval ('+ jsStr +'); and for example:
Function fn (){
} // Function declaration, which cannot be called directly
(Function fn (){
}) (); // Use () to enclose the function, you can directly call
3. Used to call a function. For example, fn ();.

Typeof Type Operators

Returns a string value: undefined type-> 'undefined', Null type-> 'object', Boolean Type-> 'boolean', Number type-> 'number', String-> 'string', built-in function Object instance-> 'function', other object types-> 'object '. (Some browsers have slightly different implementations)


1. The classification here is not very strict, such as non-bit (~) , Non-logical (!) , Delete, void, and typeof can all be regarded as unary operators, while auto-increment (++) is also classified as Arithmetic Operators in many materials. I mainly refer to the category of the original book and take into account the nature.

2. The use of the plus sign (+) is flexible. Note that, especially when used for computing, it is easy to make mistakes by ignoring the strings.

3. typeof is generally used to determine the simple data type. If it is an object type, most of the returned data is objects, which is of little practical use. However, the instanceof judgment must meet the conditions of the same context, otherwise, an error will occur. The judgment on the object category will describe the object in detail. Another more secure method will be provided.

4. First read the following code:

The Code is as follows:

Var numVal = 10.00,
StrVal = '10 ',
StrObj = new String ('10 '); (numVal = strVal); // true (typeof (strVal + strObj); // string

The first output is true, isn't it unexpected? Here, because of implicit type conversion of the = comparison operator, the Number type is converted to the String type, And the 10.00 of the Number type is not a 0 value after the decimal point, will be parsed into an integer of 10, so that the comparison will be equal. The second output is string, which is easy to understand. strVal is a string and strObj is a string object. When the two are added, the object is converted to a string. Therefore, the final result is also a string type.
5. Repeat several popular usage of symbols (this does not involve regular expressions ):
(1) Use the one-dollar plus sign (+) to convert to the Number type.
(2) Use double logic (!!) Convert to Boolean type.
(3) Use logic and (&) to check whether an object exists and perform subsequent operations.
(4) use logic or (|) to provide default values for function parameters.
(5) Use grouping () to explicitly specify as an expression.
(6) Use curly braces ({}) to define the object literal volume, JSON data format, and code block.
(7) Use brackets ([]) to define the array literal, JSON data format, access array, and access name is a property of a variable or special character.
6. Although the results of bitwise operations are not intuitive, they are highly efficient and have many interesting applications, for example, if you do not use the intermediate variable to directly exchange two values, judge the odd and even numbers, MD5 encryption, and so on, if you are interested, you can find relevant information to study on your own.
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: 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.