"Code tailor" provides technical-related information and a series of basic articles for front-end developers. Follow the "Novices of Xiaohe Mountain" public account on WeChat to get the latest articles in time.
Preface
Before starting to learn, what we want to tell you is that this article is a JavaScript
"operator" part of 060a08abb8acd8 language knowledge. If you have mastered the following knowledge items, you can skip this section and go directly to the topic exercise
- Unary operator
- Bit operator (understand)
- Boolean operators
- Multiplicative operator
- Exponent operator
- Additive operator
- Relational operator
- Equality operator
- Conditional operator
- Assignment operator
- Comma operator
- Order of operation
If you have forgotten some parts, 👇🏻 is ready for you!
What is an operator?
In ECMA-262, a set of symbols that can be used to manipulate data values are called operators
What types of operators are there
Unary operator
Operators that only operate on one value are called unary operators
1. Increment/decrement operator
- increment operator
There are two forms, namely ++i
and i++
(the two are slightly different)
let age = 29
++age
Actually equal to
let age = 29
age = age + 1 //console.log(age) = 30
The difference between i++ and ++i
- i++: Cite first and then add
- ++i: add first and then quote
- decrement operator
Similarly, i--
and --i
are also slightly different
let age = 29
--age //console.log(age) = 28
let num = 2
let num1 = 20
let sum = num-- + num1 //console.log(sum) = 22;
// 如果换成这样
let sum = --num + num1 //console.log(sum) = 21;
Note: This operator can work on any value, not limited to integers-strings, booleans, floating-point values, and even objects.
- For a string, if it is a valid numeric form, it is converted to a numeric value and then the change is applied. The variable type changes from a string to a numeric value.
- For a string, if it is not a valid numeric form, set the value of the variable to
NaN
. The variable type changes from a string to a numeric value. - For a Boolean value, if it is
false
, convert to0
and apply the change. The variable type changes from Boolean to numeric. - For a Boolean value, if it is
true
, convert it to1
and apply the change. The variable type changes from Boolean to numeric. - For floating point values, add
1
or subtract1
. - If it is an object, call its
valueOf()
method to obtain operable values. Apply the above rules to the obtained value. If it isNaN
, calltoString()
and apply other rules again. The variable type changes from an object to a numeric value.
2. One yuan plus and minus
Unary addition and subtraction operators are not unfamiliar to most developers. They are used in ECMAScript
as they are used in high school mathematics.
- one-element plus: represented by a plus sign (
+
), which is placed in front of the variable and has no effect on the value
let num = 25
num = +num
console.log(num) // 25
If it is applied to a non-numeric value, it will perform the same type conversion as Number()
Note:
- Boolean values
false
andtrue
converted to 0 and 1 - Strings are parsed according to special rules
- Objects will call their
valueOf()
and (or)toString()
methods to get convertible values
let a = '01'
let b = '1.2'
let c = 'c'
let d = false
let e = 1.2
a = +a // 变为数值1
b = +b // 变为数值1.2
c = +c // 变为NaN
d = +d // 变为数值0
e = +e // 不变
- unary minus: represented by a minus sign (
-
), which is placed in front of the variable and is mainly used to change the value into a negative value, such as converting 1 to -1.
let num = 25
num = -num
console.log(num) // -25
If applied to non-numeric values, unary minus will follow the same rules as unary plus, convert them first, and then take negative values
let a = '01'
let b = '1.2'
let c = 'c'
let d = false
let e = 1.2
a = -a // 变为数值-1
b = -b // 变为数值-1.2
c = -c // 变为NaN
d = -d // 变为数值0
e = -e // 变为-1.2
Bit operator (understand)
Low-level operations for numerical values, that is, to manipulate the bits (bits) representing data in the memory
1. Bitwise non-
The bitwise non-operator is represented by the tilde (~), and its function is to return the one's complement of the value
let num1 = 25 // 二进制 00000000000000000000000000011001
let num2 = ~num1 // 二进制 11111111111111111111111111100110
console.log(num2) // -26
2. Bitwise and
Bitwise AND is to align each bit of two numbers, and then perform the corresponding AND operation on each bit based on the rules in the truth table
let result = 27 & 4
console.log(result) // 0
/*
27 = 0000 0000 0000 0000 0000 0000 0001 1011
4 = 0000 0000 0000 0000 0000 0000 0000 0100
---------------------------------------------
AND = 0000 0000 0000 0000 0000 0000 0000 0000
*/
3. Bitwise or
The bitwise OR operator is represented by a pipe symbol (|), there are also two operands, the bitwise OR follows the truth table
let result = 27 | 4
console.log(result) // 31
/*
27 = 0000 0000 0000 0000 0000 0000 0001 1011
4 = 0000 0000 0000 0000 0000 0000 0000 0100
---------------------------------------------
OR = 0000 0000 0000 0000 0000 0000 0001 1111
*/
4. Press ectopic or
The bitwise XOR is represented by a caret (^), there are also two operands, and the bitwise XOR follows the truth table
let result = 27 ^ 3
console.log(result) // 24
/*
27 = 0000 0000 0000 0000 0000 0000 0001 1011
3 = 0000 0000 0000 0000 0000 0000 0000 0011
---------------------------------------------
XOR = 0000 0000 0000 0000 0000 0000 0001 1000
*/
5. Shift left
The left shift operator is represented by two less than signs (<<), which will move all the digits of the value to the left according to the specified number of digits
let oldValue = 2 // 等于二进制 10
let newValue = oldValue << 5 // 等于二进制 1000000,即十进制 64
Note that after shifting, 5 digits will be left at the right end of the value. Shift left will fill these empty bits with 0, so that the result is a complete 32-bit value, shift left will preserve the sign of the value it operates on
6. Signed right shift
Signed right shift is represented by two greater than signs (>>), which will shift all 32 bits of the value to the right while preserving the sign (positive or negative). Signed right shift is actually the inverse operation of left shift
let oldValue = 64 // 等于二进制 1000000
let newValue = oldValue >> 5 // 等于二进制 10,即十进制 2
7. Unsigned right shift
Unsigned right shift is represented by 3 greater than signs (>>>), which will shift all 32 bits of the value to the right. For positive numbers, unsigned right shift has the same result as signed right shift
let oldValue = 64 // 等于二进制 1000000
let newValue = oldValue >> 5 // 等于二进制 10,即十进制 2
For negative numbers, sometimes the difference can be very large. Unlike the signed right shift, the unsigned right shift will fill the space with 0, regardless of the sign bit.
let oldValue = -64 // 等于二进制 11111111111111111111111111000000
let newValue = oldValue >>> 5 // 等于十进制 134217726
/*
11111111111111111111111111000000 => 等于-64
00000111111111111111111111111110 => 等于134217726
*/
Boolean operators
1. Logical not
Operand | return value |
---|---|
Object | false |
Empty string | true |
Non-empty string | false |
Value 0 | true |
Non-zero value (including Infinity) | false |
null | true |
NaN | true |
undefined | true |
console.log(!false) // true
console.log(!'blue') // false
console.log(!0) // true
console.log(!NaN) // true
console.log(!'') // true
console.log(!12345) // false
2. Logical and
First operand | Second operand | result |
---|---|---|
Object | any | Return the second operand |
true | Object | Return the second operand |
Object | Object | Return the second operand |
null | any | If one of the operands is null, return null |
NaN | any | If one of the operands is NaN, NaN is returned |
undefined | any | If one of the operands is undefined, return undefined |
let found = true;
let clear = {};
let result = (found && clear); // 返回clear
3. Logical OR
First operand | Second operand | result |
---|---|---|
Object | any | If the first operand is an object, return the first operand |
false | Object | If the first operand evaluates to false, the second operand is returned |
Object | Object | If both operands are objects, return the first operand |
null | null | If both operands are null, return null |
NaN | NaN | If both operands are NaN, NaN is returned |
undefined | undefined | If both operands are undefined, return undefined |
let myObject = preObject || afeObject
preObject
variable contains the preferred value, and the afeObject
variable contains the alternate value
- If
preObject
is notnull
, its value will be assigned tomyObject
; - If
preObject
isnull
, theafeObject
value will be assigned tomyObject
. - This mode is often used for variable assignment
ECMAScript
Multiplicative operator
ECMAScript
defines 3 multiplicative operators: multiplication, division and modulus
1. Multiplication operator
The multiplication operator is represented by an asterisk (*) and can be used to calculate the product of two values. Its syntax is similar to C language
let result = 12 * 34
note:
Operation of returning NaN | Returns the operation status of Infinity |
---|---|
Any operand is NaN | Infinity multiplied by Infinity |
Infinity multiplied by 0 | Multiply Infinity by a non-zero finite value, then return Infinity or -Infinity according to the sign of the second operand |
2. Division operator
The division operator is represented by a slash (/) and is used to calculate the quotient of the first operand divided by the second operand
let result = 34 / 12
note:
Operand | result |
---|---|
Any operand is NaN | NaN |
Infinity divided by Infinity | NaN |
Is 0 divided by 0 | NaN |
Non-zero finite value divided by 0 | Return Infinity or -Infinity according to the sign of the first operand |
Infinity divided by any value | Return Infinity or -Infinity according to the sign of the second operand |
3. Modulo operator
The modulus (remainder) operator is represented by a percentage sign (%)
let result = 16 % 5 //余1个
Operand | return value |
---|---|
Numerical value | remainder |
If the dividend is an infinite value, the divisor is a finite value | NaN |
If the dividend is a finite value, the divisor is 0 | NaN |
If it is Infinity divided by Infinity | NaN |
If the dividend is a finite value, the divisor is an infinite value | Dividend |
If the dividend is 0, the divisor is not 0 | 0 |
If there is an operand that is not a number, first use the Number() function in the background to convert it to a number | / |
Exponent operator
ECMAScript 7
adds exponential operator (**),Math.pow()
now has its own operator, the result is the same
console.log(Math.pow(4, 2); // 16
console.log(4 ** 2); // 9
console.log(Math.pow(16, 0.5); // 4
console.log(16 ** 0.5); // 4
Additive operator
Additive operators, namely addition and subtraction operators, are generally the simplest operators in programming languages
1. Addition operator
First operand | Second operand | return value |
---|---|---|
Numerical value | NaN | NaN |
Infinity | Infinity | Infinity |
-Infinity | -Infinity | -Infinity |
Infinity | -Infinity | NaN |
+0 | +0 | +0 |
-0 | +0 | +0 |
-0 | -0 | -0 |
String | String | Spliced together |
String | any | Convert the second operand to a character, and then concatenate it with the first operand |
Note: The first operand and the second operand have no specific order
let result = 10 + 10 // 20
let result2 = 10 + '5' // 105
2. Subtraction operator
First operand | Second operand | return value |
---|---|---|
Numerical value | NaN | NaN |
Infinity | Infinity | NaN |
-Infinity | -Infinity | NaN |
Infinity | -Infinity | Infinity |
-Infinity | Infinity | -Infinity |
+0 | +0 | +0 |
-0 | +0 | -0 |
-0 | -0 | +0 |
Supplement: If any operand is a string, Boolean value, null
or undefined
Number()
in the background to convert it to a number, and then perform mathematical operations according to the previous rules
let result1 = 6 - true // true 被转换为 1,所以结果是 5
let result2 = NaN - 2 // NaN
let result3 = 6 - 3 // 3
let result4 = 6 - '' // ""被转换为 0,所以结果是 6
let result5 = 3 - '2' // "2"被转换为 2,所以结果是 1
let result6 = 2 - null // null 被转换为 0,所以结果是 2
Relational operator
Relational operators perform operations that compare two values, including less than (<), greater than (>), less than or equal to (<=), and greater than or equal to (>=), and the usage is the same as in math class
let result1 = 6 > 3 // true
let result2 = 4 < 3 // false
Operand | Behave |
---|---|
Are all numbers | Numerical comparison |
Are all strings | Compare the encoding of the corresponding characters in the string one by one |
Any operand is a number | Then convert the other operand to a numeric value and perform numeric comparison |
Any operand is an object | Call its valueOf() method, if there is no valueOf() method, call the toString() method, and then perform the comparison according to the previous rules after the result is obtained |
Either operand is a boolean | Convert it to a number and then perform the comparison |
//补充:
let result1 = NaN < 5 // false
let result2 = NaN >= 5 // false
Equality operator
Determining whether two variables are equal is one of the most important operations in programming
ECMAScript
provides two sets of operators. The first group is that is equal to and not equal to , they perform conversion before comparing. The second group is congruent and insufficiency , they do not perform conversion prior to the comparison.
1. Equal to and not equal to
The equal operator is represented by two equal signs (==), if the operands are equal, it will return trueThe inequality operator is represented by an exclamation mark and an equal sign (!=). If the two operands are not equal, it will return true
Operand | Behave |
---|---|
Either operand is a boolean | Convert it to a numeric value and compare whether it is equal (false :0 true :1) |
String + number | Try to convert the string to a number, and then compare for equality |
One operand is an object, the other operand is not | Call the valueOf() method of the object to get its original value, and then compare it according to the previous rules |
Any operand is NaN | Equality operator returns false, inequality operator returns true |
Both operands are objects | Compare whether they point to the same object |
Supplement: (1) NaN
not equal to NaN
(2) null
and undefined
are equal
(3) null
and undefined
cannot be converted to other types of values and then compared
2. congruent and
The congruent and incongruent operators need to be congruent or incongruent when the comparison number is not converted before returning true
let result1 = '34' == 34 // true,转换后相等
let result2 = '34' === 34 // false,不相等,因为数据类型不同
let result1 = '23' != 23 // false,转换后相等
let result2 = '23' !== 23 // true,不相等,因为数据类型不同
let result1 = null == undefined // true
let result1 = null === undefined // false,不是相同的数据类型
Conditional operator
Conditional operator is one of the most widely used operators in ECMAScript
let min = num1 < num2 ? num1 : num2
//如果 num1 小于 num2 ,则返回num1 ,否则返回num2
Assignment operator
Simple assignment is represented by an equal sign (=), which assigns the value on the right hand side to the variable on the left hand side
let num = 100
Every mathematical operator and some other operators have corresponding compound assignment operators
Divide value after multiplication | *= |
---|---|
Assign after division | /= |
Assignment after taking the modulus | %= |
Assignment after addition | += |
Assignment after subtraction | -= |
Assign after shift left | <<= |
Assign after right shift | \>>= |
Assign after unsigned right shift | \>>>= |
Comma operator
The comma operator can be used to perform multiple operations in one statement
let num0 = 1,
num1 = 2,
num2 = 3
Order of operation
1. Priority
The precedence level of various operators in JavaScript (Operator Precedence) is different. Operators with higher precedence are executed first, and operators with lower precedence are executed later.
3 + 1 * 2 // 6
In the code above, the multiplication operator ( *
) has a higher priority than the addition operator ( +
), so the multiplication is performed first, and then the addition is performed.
This is a very simple priority question, but it is often confusing if multiple operators are mixed together.
var x = 1
var array = []
var y = array.length <= 0 || array[0] === undefined ? x : array[0]
priority |
---|
Less than or equal to (<=) |
Strictly equal (===) |
Or (||) |
Three yuan (?:) |
Equal sign (=) |
//因此上述代码实际运算是这样的
var y = array.length <= 0 || array[0] === undefined ? x : array[0]
Note: It is not necessary to remember the precedence of all operators, just query when they are used.
2. Left binding and right binding
For operators with the same precedence level, in most cases, the order of calculation is always from left to right. This is called the "left-to-right associativity" of the operator, that is, the calculation starts from the left.
a + b + c
It’s very simple like this. First calculate the a
and b
on the left, and then calculate the sum with c
However, the calculation order of some operators is from right to left, that is, starting from the right. This is called the "right associativity" of operators. There are mainly assignment operators ( =
) and ternary conditional operators ( ?:
)
h = x = y = z
i = a ? b : c ? d : e ? f : g
// <==等价于==>
h = x = y = z
i = a ? b : c ? d : e ? f : g
Question self-test:
1: What does the following code output?
;+true
!'Lydia'
- A:
1
andfalse
- B:
false
andNaN
- C:
false
andfalse
2: What does the following code output?
function sum(a, b) {
return a + b
}
sum(1, '2')
- A.
NaN
- B.
TypeError
- C.
"12"
- D.
3
3: What does the following code output?
!!null
!!''
!!1
- A.
false
true
false
- B.
false
false
true
- C.
false
true
true
- D.
true
true
false
4: What does the following code output?
console.log(3 + 4 + '5')
- A.
"345"
- B.
"75"
- C.
12
- D.
"12"
Problem analysis
One,
Answer: A
+
number operator converts true
to Number
type 1
And string
type Lydia
converted to Boolean
value is true
, and there is !
, so return false
two,
Answer: C
When the +
operator encounters the addition of a value and a string, the value is converted into a string, and then spliced
three,
Answer: B
null
is false
. !null
returns true
. !true
returns false
.
""
is true
. !""
returns true
. !true
returns false
.
1
is true
. !1
returns false
. !false
returns true
.
four,
Answer: B
Operator associativity is the order in which the compiler evaluates expressions, from left to right or from right to left. This happens only when all operators have the same precedence. We only have one operator: +
. In addition, the relevance is from left to right.
Calculate 3+4 first. The result is the number 7.
7+"5" is implicitly converted to "75". JavaScript
converts the number 7 into a string, we can use the +
operator to concatenate the two strings.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。