This is the seventh day of my participation in the August More text Challenge. For details, see:August is more challenging

Hello everyone, I am the prosperity of the other shore 🌸, a front-end 👨🏻💻 that firmly believes that hard work can change destiny. If I have the honor to write an article that can get your favor, I am very lucky ~

This series of articles was first published in nuggets

Writing in the front

In this article, we’ll learn about operators in JavaScript. Here’s what we’ll learn from this chapter

This article covers the new operators in ECMAScript6. The content is an extension and is written here for a comprehensive understanding of operators in JavaScript.

An overview of the

What is a JavaScript operator

Operators are used to operate on one or more operands. For example, 1+2, where the operands are 2 and 3 (operands are also called operands), and the operator is the + sign.

Operators in JavaScript mostly consist of punctuation marks such as +, -, *, etc. But it’s not just symbols. There are also keywords, such as the Typeof operator we studied earlier.

Classification of operators

Operators in JavaScript can be classified by the number of operands or by their function.

By number of operands:

  • Unary operator: An operator that operates on only one operand, such as the increment operator, typeof operator, etc.

  • Binary operator: An operator that operates on only two operands, such as the addition operator, logic and operator, etc.

  • Ternary operator: An operator, such as a conditional operator, that can operate on three operands

Classification by function:

  • Arithmetic operator

  • Comparison operator

  • Assignment operator

  • Logical operator

  • .

Operator precedence

When multiple operators are used in JavaScript, the final result of execution may be different due to the order in which each operator is executed.

For example, the following code:

4 + 3 * 2 / / 10
(4 + 3) * 2 / / 14
Copy the code

We can see that the final result varies depending on the order of execution.

The priority of the operators in JavaScript looks like this:

Note: The priority diagrams for the above operators are provided by the MDN community.

Due to the large number of operators in JavaScript, it is often difficult to remember the priority of specific operators. In actual development, there is a small trick to include the operators that need to be calculated first with () to achieve the purpose of calculating first.

Arithmetic operator

There are roughly eight arithmetic operators in JavaScript, as shown in the figure below:

So now we’re going to show you how to use these 8 operators. Okay

Addition operator+

In addition to adding numbers, there are two other ways to do this: implicit conversions to numbers and concatenation of strings. Let’s take a look at how to do this:

  1. numberType add operation:
var num1 = 20
var num2 = 30

console.log(num1 + num2) / / 50
Copy the code
  1. Implicit type conversion:
console.log(+'123') / / 123
console.log(+true) / / 1
Copy the code
  1. String concatenation (if one of the operators is not the operator twicenumberType whose operator is used to concatenate strings) :
console.log('1' + true) // 1true
console.log(100 + '200') / / 100200
Copy the code

String concatenation is what we learned earlier when we implicitly convert to string

The subtraction operator-

The subtraction operator in JavaScript performs two functions: one is to subtract from the number type, and the other is to implicitly convert to the number type and invert it (or directly if it is a number).

  1. numberSubtraction of type:
var num1 = 20
var num2 = 30

console.log(num1 - num2) / / - 10
console.log(num2 - num1) / / 10
Copy the code
  1. Implicit type conversion
console.log(-'123') / / - 123
console.log(-true)  // -1
console.log(-Awesome!)   / / - 666
Copy the code

Multiplication operator*And division operator/

In JavaScript, the multiplication and division operators * and/work just as they do in math. The code looks like this:

console.log(10 / 2) / / 5
console.log(10 * 2) / / 20

console.log(2 / 10) / / 0.2
console.log(10 * 0.2) / / 2

Copy the code

Exponential operator天安门事件

In JavaScript, the exponent operator is used to calculate the base to the exponent. For example, if we want to calculate 2 to the power of 10, we would write 2**10 as follows:

// 2 to the 10th
console.log(2天安门事件10) / / 1024
Copy the code

Modulo operator%

The mod operator, also known as the mod operator, is used to calculate the remainder after the division of two operands. The operator can be negative.

console.log(10 % 3) / / 1

// The operator has a negative number
console.log(-5 % 2) // -1
console.log(5 % -2) / / 1
console.log(-5 % -2) // -1
Copy the code

The increment operator++And the decrement operator--

The increment operators ++ and decrement operators provided in JavaScript — both unary operators do the following:

  • Increment operator: Adds an operator (operand) to 1

  • Decrement operator: decrement the operator (operand) -1

There are two types of increment and decrement operators: preposition and postposition. The differences are as follows:

  • Pre-operator: A pre-operator is an operator that comes after the pre-operator (operand). The pre-operator evaluates first and returns the result

  • Postoperands: A postoperand is one in which the former operator (operand) comes after the former operator. The postoperator returns the value of the current operator (operand) before calculating it

The example code is as follows:

  1. The increment operator
var x = 3
var y = 3

console.log(++x) / / 4
console.log(y++) / / 3

console.log("The value of x is:" + x + ", the value of y is: + y) // The value of x is: 4 and the value of y is: 4
Copy the code

> We can see that the final results are all 4, but the results are inconsistent during the process

  1. Decrement operator
var x = 3
var y = 3

console.log(--x) / / 2
console.log(y--) / / 3

console.log("The value of x is:" + x + ", the value of y is: + y) // The value of x is: 2 and the value of y is: 2
Copy the code

“> < p style =” max-width: 100%; clear: both

Comparison operator

The JavaScript comparison operator is used to compare two operands (operands). The operands can be of any type. If they are not of the same type, they are cast, compared, and return a Boolean value indicating whether the specified condition is met.

There are 8 comparison operators in JavaScript, as shown in the figure below:

Is greater than>And less than<, greater than or equal top, less than or equal toOr less

These four operators are fairly simple and mathematically similar, but it is important to note that when comparing two string values, the comparison is to their Unicode code.

The example code is as follows:

console.log(10 > 8) // true

// True will be automatically converted to number type 1, false will be automatically converted to number type 0
console.log(true > false) // true

// String compares the size of the Unicode code
console.log('A' > 'a') // false

// The string 111 is automatically converted to number
console.log(123 > '111') // true
Copy the code

It’s the same thing with the other three.

Is equal to the= =And is not equal toindicatesThe operator

The equal == and not equal ≠ operators compare whether the values of two operands (operands) are equal. They do not compare types. That is, 2 and ‘2’ are equal. The example code is as follows:

console.log(true= =1) // true

console.log(2= ='2') // true

console.log(1= =true) // true

console.log([] == ' ') // true
Copy the code

In the above code, each comparison is preceded by a cast to the same data type before the comparison. It is worth noting that an empty array is equal to an empty string, because an empty array converted to a string is an empty string.

console.log(typeof String([])) // string
Copy the code

We’ll talk about arrays later

Are congruent= = =And not congruentIndicates a =The operator

JavaScript provides the equal and not equal operators that only compare values, but not types. This can lead to detailed errors in development, such as:

We want to compare 1 to ‘1’ and add them if they are equal. We can see that the two values are not equal, but using the equals operator in JavaScript results in true, and the result of the sum is string concatenation. Sample code if required:

var str = '1'
var num = 1

// Conditional statement
if (str == num) {
    console.log(str + num) / / 11
}
Copy the code

We actually want the result to be of type number, but since we are comparing a number to a string, the addition operator is doing string concatenation, so it ends up with a string value, which is obviously not what we want.

We’ll learn about conditional statements next time

The congruent and incongruent operators provided in JavaScript help solve this problem. The example code looks like this:

var str = '1'
var num = 1

console.log(str === num) // false
Copy the code

Now we can solve the problem we have up there.

Logical operator

There are only three logical operators in JavaScript, as shown in the figure below:

The main operands (operands) used by the logical operator are Boolean values. If they are not Boolean values, they are automatically converted to Boolean values. For details on what values are automatically converted to Boolean values, see convert to Boolean.

The logical operators in JavaScript are used as follows:

Logic is not!The operator

The logical non-operator in JavaScript is a unary operator written with an Exclamation mark (!). , its functions are as follows:

Return false if the value of the operand (operand) converted to Boolean is true; Return true if the value of the operand (operand) converted to Boolean is false. In short, take the reverse.

The example code is as follows:

console.log(!true)   // false
console.log(!false)  // true
console.log(!0)      // true
console.log(!1)      // false
console.log(!' ')     // true
Copy the code

Logic and operators&&

The logic and operator is represented by two ampersand symbols that operate on two operands (operands) and return a Boolean value.

The two operands involved in the calculation are automatically converted to Boolean if they are not of type.

The logic and operators are computed as follows:

  • If the value of the left operand is true and the value of the right operand is true, the final result is true

  • If either of the values of the left and right operands is false, the final result is false.

The example code is as follows:

console.log(true && true)    // true
console.log(true && false)   // false
console.log(false && true)   // false
console.log(false && false)  // false
Copy the code
  • If the value of the left-hand operand converted to a value of type Boolean is true, the right-hand operand is returned.

  • If the value of the left operand converted to a value of type Boolean is false, the left operand is returned directly.

It is important to note that if an lvalue of false is detected, the result is returned without further execution (useful in real development).

The example code is as follows:

console.log(1 && 2) / / 2
console.log(0 && 1) / / 0
console.log(1 && ' ') / /"
console.log(true && 'str') // 'str'


If the lvalue is false, the execution will not proceed. Otherwise, an error message will be displayed with the following message: value is not defined
console.log(false && value) // false
Copy the code

Logical or operator||

Logic or the operator USES two | symbol, its effect is also used for computing the two operands (operands) and returns a Boolean value of type.

The calculation rules of logical or are as follows:

  • If the value of the left-hand operand is true, the final result is true

  • If the value of the left operand is false, the final result is the right operand

  • If the value of the left operand converted to a value of type Boolean is true, the left operand is returned.

  • If the value of the left-hand operand converted to a value of type Boolean is false, the right-hand operand is returned.

The example code is as follows:

console.log(true || true)    // true
console.log(true || false)   // true
console.log(false || true)   // true
console.log(false || false)  // false


console.log(1 || 2) / / 1
console.log(0 || 1) / / 1
console.log(1 || ' ') / / 1
console.log(true || 'str') // true

Copy the code

Assignment operator

The assignment operator is to assign the result of the expression on the right to the variable on the left. The = operator we used before is the assignment operator. In addition to this operator, JavaScript also has the following assignment operators

Except for the = sign, the rest are collectively called compound assignment operators.

Compound assignment operator

The so-called compound assignment operator is short for the arithmetic operator and the assignment operator. Here we take the addition assignment operator as an example. The syntax structure is as follows:

x += y
Copy the code

The syntax above is the same as for x = x + y, that is, a compound numeric operator that performs some kind of calculation between the right-hand operand (operand) and the left-hand operand (operand) and assigns the result to the left-hand operator.

The example code is as follows:

var num = 10

var result1 = 20
var result2 = 20


// The addition assignment operator
result1 += num
result2 = result2 + num

console.log(result1 === result2) // true


// Subtraction assignment operator
result1 -= num
result2 = result2 - num

console.log(result1 === result2) // true


// The exponential assignment operator
result1 **= num
result2 = result2 ** num

console.log(result1 === result2) // true
Copy the code

Chain assignment

The JavaScript language supports chained assignment. What is chained assignment? Just look at the code below

var a = 10
var b = 20
a += b -= 10
console.log(a) / / 20
Copy the code

A chain assignment assigns values from right to left. In the above code, we first calculate the value b -= 10, assign it to b, and then calculate a += b, so the final result is 20.

Other operators

In addition to which of the above operators have their own family of operators, there are some special operators that are always going it alone, but are important in practical development, so let’s take a look at which operators are included

Conditional operator? :

The conditional operator in JavaScript, the only ternary operator in JavaScript, has the following syntax:

Conditions? value1Value:2
Copy the code

This expression returns the value 1 when the condition is true or can be cast to true; otherwise, this expression returns the value 2.

The example code is as follows:

var age = 20
var result = age > 18 ? 'Adult' : 'Minor'
console.log(result) / / adult
Copy the code

In the above code, since our variable age has a value of 20, which is greater than 18, the result of the expression part is true, and we end up assigning the adult to the result variable

Conditional operator chains

Not only is the conditional operator the only ternary operator, but the third expression of the conditional operator can also be a conditional operator, and so on, forming a chain. This is called a chain of conditional operators. The example code is as follows:

var score = 85
var result = score >= 90 ? 'good'
    : score >= 80 ? 'good'
        : score >= 60 ? 'qualified' : 'Not up to standard'


console.log(result) / / good
Copy the code

Score >= 90 = false, so score >= 80? Score >= 60? If score >= 80 is true, the final result is good. If score >= 80 is false again, the final result is good. If score >= 80 is true, the final result is good.

A chain of conditional operators is also called a nested structure of conditional operators.

Grouping operator(a)

In JavaScript, () is the grouping operator, which has the highest priority among all operators. This operator has no other meaning than that certain expressions can be executed first. The example code is as follows:

var result1 = 1 + 2 * 3 / 4 % 5天安门事件6
/ * * * the above order for the execution of the order of 16 * index operator, to perform 5 6 results for 15625 * * *, die execution order of 15, here since 2 * 3 from left to right in turn perform calculation * the order of 14 addition * /
console.log(result1)

// You can get different results by grouping ()
var result2 = ((1 + 2) * 3 / 4 % 5) * *6
/** * we can execute */ from left to right by using ()
console.log(result2,)
Copy the code

New operators in ES6 (extension)

Many new operators have been added in ES6. Here are some commonly used operators, as shown below:

Note: ES6 is simply an umbrella term for ECMAScript2015 releases

There are some things that we haven’t touched on yet, such as arrays and objects, but the purpose of recording these operators here is to make this article more collectible.

Expansion operator.

The expansion operator is three dots (…) , the expansion operator is divided into object expansion operator and array expansion operator.

Array expansion operator

The array expansion operator converts an array to a comma-separated argument list. The example code is as follows:

// Define an array

var arr = [1.2.3.4.5]


console.log(... arr)// 1, 2, 3, 4, 5
// The reason we get 1, 2, 3, 4, 5 is because we expanded the array into a list divided by, and this is used as an argument, as below

console.log(1.2.3.4.5) // 1, 2, 3, 4, 5
Copy the code

Deep copy an array

We can use the expansion operator to make a deep copy of an array as follows:

// Define an array

var arr = [1.2.3.4.5]

/ / shallow copy
var arr1 = arr

/ / copy
var arr2 = [...arr]

// The shallow copy is the same as the original array when the comparison is made
console.log(arr1 === arr);
// A deep copy is different from the original array
console.log(arr2 === arr);
/** * This is because the shallow copy copies the memory address, while the deep copy copies the actual value */

// When we modify the original array, the shallow copy will change its value, but the deep copy will not
arr[0] = 10 // Change the first value of the array to 10
console.log(arr1) // [10, 2, 3, 4, 5]
console.log(arr2) // [1, 2, 3, 4, 5]

Copy the code

Details on depth copy will be explained later

Object expansion operator

In ECMAScript2018, the expansion operator was introduced for use in objects. In addition to expanding an object, it can also be used to read the remaining properties of structures when they are assigned. The example code is as follows:

// Define an object
var person = {
    name: 'Prosperity on the other side'.hobby: 'coding'.age: 18
}

// Deep copy an object
varperson2 = { ... person }// When the structure is assigned, it accepts the remaining value
var{ name, ... obj } = personconsole.log(name, obj) // {hobby: 'coding', age: 18}
Copy the code

It is worth noting that the expansion operator can only copy its own properties, not those inherited from the prototyped object.

Null value merge operator??

The null merge operator, represented by two question marks, is also a logical operator, similar to the logical or operator. It is computed by returning the right operand as long as the left operand is null or undefined, and otherwise returning the left operand. The logical or operator only returns the right operand if the left operand is converted to false.

The example code is as follows:

console.log(null ?? 10) / / 10
console.log(undefined ?? 10) / / 10
console.log(false ?? 10) // false
Copy the code

This operator is useful for assigning a value to a variable that has no value. For example, if the number has no value, assign it a value. Otherwise, do not assign a value.

var value

// Assign 10 to value if it is not null or undefined
value = value ?? 10
console.log(value) / / 10
Copy the code

It is worth noting that the null-value merge operator cannot be used with the logical and and or, otherwise an exception will be thrown. The solution is to indicate precedence by using ()

Browser compatibility is as follows:

Above from: Can I Use

Null merge assignment operator?? =

Our above value = value?? 10 can be shortened to value?? = 10. The null-merge assignment operator, also a type of compound assignment operator, is intended to simplify this approach.

Browser compatibility is as follows:

Above from: Can I Use

Logic and assignment operators&& =And logic or assignment operators| | =

Logic and the assignment operator and the logic or the assignment operator | | = is also a kind of compound assignment operator, the purpose of it is to simplify the code. The example code is as follows:

var x = 0;
var y = 1;

x &&= 0; / / 0
x &&= 1; / / 0
y &&= 1; / / 1
y &&= 0; / / 0
// The above code is equivalent to
x = x && 0
x = x && 1
y = y && 1
y = y && 0
Copy the code

The browser compatibility for &&= is as follows:

| | = browser compatibility is as follows:

Above from: Can I Use

Optional chain operator? .

Optional chain operator is used to read A certain object chain deep under the value of the attribute, use the operator do not have to verify object under each attribute must exist, for example, when we want to visit A.A.B this property, the first thing we need to ensure that A exist, then you need to ensure that A.a exist, can access A.A.B this property, or it will be an error.

There is no such problem with the optional chain operator, which returns undefind without an error when we access a property, as long as one of the properties is not present.

var A = {}

// console.log(A.A.B) // Error

console.log(A.a? .b)// undefined
Copy the code

The optional chain operator can also be used to call methods on an object. The example code is as follows:

var obj = {}

// If the obj.fun() method exists, the following method is called directly; if it does not exist, undefined is returnedobj.fun? .A()Copy the code

Browser compatibility is as follows:

Above from: Can I Use

Numeric separator_

The numeric separator (_) is not strictly an operator. It is used to make numbers easier to read, such as the code below

console.log(1 _0000_0000) / / 100000000
Copy the code

This notation is just for the purpose of being easy to read. It doesn’t matter what the result is. Look at the code below

1 _1= = =11 // true
Copy the code

The browser compatibility is as follows:

Above from: Can I Use

conclusion

Preview: We’ll look at conditionals in JavaScript in the next article

Excellent articles

04- Understand basic data types in JavaScript

03- This time I figured out variables in JavaScript

02-JavaScript lexical structure

01- What is JavaScript