The operator

We know many operators from school, such as plus +, times *, minus – and so on.

In this chapter, we will focus on some operators that are not covered in school math courses.

Terminology: “unary operator”, “binary operator”, “operand”

Before we begin, let’s take a quick look at common terms.

  • Operator-the object to which the operator applies. For example, the multiplication operation 5 * 2 has two operators: left operand 5 and right operand 2. Sometimes they’re called “metrics.”

  • An operator is unary if it corresponds to only one operator. Take the unary negation – operator, which converts numbers:

    let x = 1;
    
    x = -x;
    alert( x ); // the unary negative operator is in effect
    Copy the code
  • An operator is a binary operator if it has two operators. The minus sign also has binary operator form:

    let x = 1, y = 3;
    alert( y - x ); // 2, the binary operator minus is subtracted
    Copy the code

    Strictly speaking, in the example above, we use the same symbol to represent two different operators: the minus operator, which is the unary operator that reverses the sign, and the subtraction operator, which is the binary operator that subtracts one number from another.

String concatenation function, binary operator +

Next, let’s take a look at JavaScript operator features outside the scope of school math.

In general, the plus sign is used for summation.

But if the plus sign + is applied to a string, it merges (concatenates) the strings:

let s = "my" + "string";
alert(s); // mystring
Copy the code

Note: As long as one of the operands is a string, the other operand is also converted to a string.

Here’s an example:

alert( '1' + 2 ); / / "12"
alert( 2 + '1' ); / / "21"
Copy the code

As you can see, strings before and after do not affect this rule. Simply put: If any operand is a string, the other operand will be converted to a string.

Note, however, that operators operate from left to right. If it is two numbers followed by a string, the two numbers are added before being converted to a string:

alert(2 + 2 + '1' ); // "41" instead of "221"
Copy the code

String concatenation and conversion is a property of the binary operator plus +. All other mathematical operators work only on numbers. Usually, they convert the operands into numbers.

For example, subtraction and division:

alert( 2 - '1' ); / / 1
alert( '6' / '2' ); / / 3
Copy the code

Number conversion function, unary operator +

Plus plus has two forms. One is the binary operator we just discussed above, and the other is the unary operator.

The unary operator plus, or plus +, applies to a single value and has no effect on numbers. But if the operand is not a number, the plus sign converts it to a number.

Such as:

// Not valid for numbers
let x = 1;
alert( +x ); / / 1

let y = 2 -;
alert( +y ); / / - 2

// Convert non-numbers
alert( +true ); / / 1
alert( +"" );   / / 0
Copy the code

Its effect and Number(…) Same, but shorter.

We often have a need to convert strings to numbers. For example, if we are evaluating from an HTML form, we usually get a string. What if we want to Sue for peace?

The binary operator plus merges them into strings:

let apples = "2";
let oranges = "3";

alert( apples + oranges ); // "23", binary operator plus sign merge string
Copy the code

If we want to treat them as numbers, we need to transform them and sum them:

let apples = "2";
let oranges = "3";

// All values are converted to numbers before the binary plus operator takes effect
alert( +apples + +oranges ); / / 5

// Longer
// alert( Number(apples) + Number(oranges) ); / / 5
Copy the code

From a mathematician’s point of view, a lot of plus signs can be strange. But from a programmer’s point of view, it’s no surprise: the unary plus operator works first, they convert strings to numbers, and then the binary plus operator sums them up.

Why do unary operators operate on operators before binary operators? As we will discuss later, this is due to their higher priority.

Operator priority

If an expression has more than one operator, the order of execution is determined by priority. In other words, precedence is implicit in all operators.

Since elementary school, we have known that multiplication precedes addition in the expression 1 + 2 * 2. This is a matter of priorities. Multiplication has a higher priority than addition.

Parentheses have the highest precedence, so if we are not satisfied with the existing order of operations, we can use parentheses to change the order of operations, like this :(1 + 2) * 2.

There are many operators in JavaScript. Each operator has a corresponding priority number. The larger the number, the earlier the execution. If the priorities are the same, they are executed from left to right.

Here’s an excerpt from Mozilla’s priority table (you don’t have to remember it all, but remember that unary operators take precedence over binary operators) :

priority The name of the symbol
. . .
16 Unary plus +
16 Unary minus -
14 Multiplication sign *
14 devide /
13 A plus sign +
13 A minus sign -
. . .
3 The assignment operator =
. . .

We can see that “unary operator plus” has priority 16, which is higher than “binary operator plus” at priority 13. This is why the unary plus in the expression “+apples + +oranges” works first before binary addition.

The assignment operator

We know that the assignment symbol = is also an operator. You can see from the priority table that it has a very low priority of 3.

That’s why, when we assign a value, say, x = 2 * 2 + 1, we do all the evaluations first, then we do lambda, and we store the results in x.

let x = 2 * 2 + 1;

alert( x ); / / 5
Copy the code

Chain assignment is also possible:

let a, b, c;

a = b = c = 2 + 2;

alert( a ); / / 4
alert( b ); / / 4
alert( c ); / / 4
Copy the code

Chain assignment is performed from right to left. The rightmost expression 2 + 2 is executed first, and the result is assigned to the left: c, b, and a. Finally, all variables share a value.

The assignment operator= \ \ ""Will return a value

Each operator has a return value. This is obvious for most operators, such as plus + or times *. The same is true for assignment operators.

The statement x = value writes the value of value to x and returns x.

Here is an example of using assignment in a complex statement:

let a = 1;
let b = 2;

let c = 3 - (a = b + 1);

alert( a ); / / 3
alert( c ); / / 0
Copy the code

In the example above, (a = b + 1) results in the value assigned to A (i.e., 3). This value is then used for further operations.

Isn’t this code fun? We should understand how it works, because we sometimes see it in third-party libraries, but we shouldn’t write it ourselves. Such tricks make code very uncluttered and unreadable.

The remainder operator %

The % operator has nothing to do with percentages, even though it looks like a percent sign.

A % b is the remainder of a divided by b.

Here’s an example:

alert( 5 % 2 ); // 1 is the remainder of 5/2
alert( 8 % 3 ); // 2 is the remainder of 8/3
alert( 6 % 3 ); // 0 is the remainder of 6/3
Copy the code

The power operator **

The power operator ** is a recent addition to JavaScript.

For the natural number b, the result of a ** b is a multiplied by itself b times.

Here’s an example:

alert( 2六四屠杀2 ); // 4 (2 * 2)
alert( 2六四屠杀3 ); // 8 (2 * 2 * 2)
alert( 2六四屠杀4 ); // 16 (2 * 2 * 2)
Copy the code

This operator still works if a and b are non-integers.

Such as:

alert( 4* * (1/2));// 2.
alert( 8* * (1/3));// 2 (1/3 power equals open third)
Copy the code

Add/subtract

The addition or subtraction of a number is one of the most common mathematical operators.

So, there are special operators for this:

  • Add the variable to 1:

    let counter = 2;
    counter++;      // Same as counter = counter + 1, but cleaner
    alert( counter ); / / 3
    Copy the code
  • Decrement — subtract a variable from 1:

    let counter = 2;
    counter--;      // Same as counter = counter - 1, but cleaner
    alert( counter ); / / 1
    Copy the code

Note:

Add/subtract can only be applied to variables. Try applying it to a value (such as 5++) and an error will be reported.

The operators ++ and — may precede or follow variables.

  • When an operator is placed after a variable, it is called “post-form” :counter++.
  • When an operator precedes a variable, it is called the “leading form” :++counter.

Both do the same thing: add the variable counter to 1.

So are they different? Yes, but we can only see the difference if we use the return value of ++/–.

Tell me more. We know that all operators return values. Self-addition/subtraction is no exception. The pre-form returns a new value, but the post-form returns the original value (before addition/subtraction).

To see the difference, look at the following example:

let counter = 1;
let a = ++counter; / / (*)

alert(a); / / 2
Copy the code

(*) is preceded by ++counter. Add counter to return the new value 2. So alert says 2.

Let’s look at the post-form:

let counter = 1;
let a = counter++; // (*) change ++counter to counter++

alert(a); / / 1
Copy the code

The line on which (*) is placed is the post-form Counter ++, which also adds counter, but returns the old value (before the addition). So alert says 1.

Conclusion:

  • If the add/subtract values are not used, the form is the same:

    let counter = 0;
    counter++;
    ++counter;
    alert( counter ); // 2, these two lines have the same effect
    Copy the code
  • If we want to append the variable and need to use the append value immediately, then we need to use the pre-form:

    let counter = 0;
    alert( ++counter ); / / 1
    Copy the code
  • If we want to add one to a number, but we want to use the value before we add it to it, we need to use the post-form:

    let counter = 0;
    alert( counter++ ); / / 0
    Copy the code

Comparison of autoaddition/subtraction and other operators

The ++/– operator can also be used inside expressions. They have a higher priority than most arithmetic operators.

Here’s an example:

let counter = 1;
alert( 2 * ++counter ); / / 4
Copy the code

Compare this with the example below:

let counter = 1;
alert( 2 * counter++ ); // 2, because counter++ returns "old value"
Copy the code

Although technically possible, this makes the code less readable. Multiple operations on a single line — that’s not good.

When reading code, a quick visual “vertical” scan can easily miss counter++, and such augmentation is not obvious.

We recommend the “one action in a row” pattern:

let counter = 1;
alert( 2 * counter );
counter++;
Copy the code

An operator

Bitwise operators treat operators as 32-bit integers and operate on their binary representation.

These operators are not specific to JavaScript. Most programming languages support these operators.

Here are the bit operators:

  • Bitwise and (& )
  • The bitwise or (| )
  • Bitwise xOR (^ )
  • The bitwise not (~ )
  • Shift to the left (<< )
  • Moves to the right (>> )
  • Unsigned right shift (>>> )

These operations are used very sparingly. To understand them, we need to explore the underlying numerical representation, and now is not the best time to do that. Especially since we’re not going to use it right now. If you are interested, you can read about bitwise operators in MDN. It’s better to read when you have a practical need.

Modify and replace

We often need to operate on a variable and store the new result of the calculation in the variable.

Here’s an example:

let n = 2;
n = n + 5;
n = n * 2;
Copy the code

This operation can be simplified by using the operators += and *= :

let n = 2;
n += 5; // now n = 5
n *= 2; // now n = 14 (same as n = 2)

alert( n ); / / 14
Copy the code

The short “modify and replace” operator works for all operators, including bitwise operators: /=, -=, and so on.

These operators have the same precedence as normal assignment operators, so they run after most of the other operations have finished:

let n = 2;

n *= 3 + 5;

alert( n ); // if (n *= 8)
Copy the code

Comma operator

The comma operator is one of the rarest and least commonly used operators. Sometimes it is used to write shorter code, so in order to be able to understand the code, we need to understand it.

The comma operator allows us to process multiple statements, use them, and separate them. Each statement is run, but only the result of the last statement is returned.

Here’s an example:

let a = (1 + 2.3 + 4);

alert( a ); // 7 (3 + 4)
Copy the code

Here, the first statement 1 + 2 runs, but its result is discarded. 3 + 4 is then computed and the result is returned.

The comma operator has a very low priority

Note that the comma operator has a very low priority, even lower than =, so parentheses are very important in your example above.

If there are no parentheses: a = 1 + 2, 3 + 4 executes + first, sums the values to a = 3, 7, then the assignment operator = executes, ‘a = 3’, then the value 7 after the comma is not executed, it is ignored. That’s the same thing as a is 1 plus 2, 3 plus 4.

Why do we need an operator that returns only the last value?

Sometimes, people use it to perform complex operations by putting several operations on a single line.

Here’s an example:

// There are three operators on one line
for (a = 1, b = 3, c = a * b; a < 10; a++) {
 ...
}
Copy the code

This technique is used in many JavaScript frameworks, which is why we mention it. But it usually doesn’t improve the readability of your code, so think about it before you use it.

Homework assignments

Do the questions yourself and then look at the answers.

1. Post-and pre-operators

Importance: ⭐️⭐ ⭐️⭐️

What are the final values of variables A, B, c, and D in the following code?

let a = 1, b = 1;

let c = ++a; // ?
let d = b++; // ?
Copy the code

2. Result of assignment

Importance: ⭐️⭐️ ️

What are the values of a and x in the following code after it has been run?

let a = 2;

let x = 1 + (a *= 2);
Copy the code

Think about it, write them down and compare them with your answers.

The answer:

Reply 1-2-7 in the background of wechat public account “Technology Chat” to obtain the answer to this question.


Modern JavaScript Tutorials: Open source modern JavaScript tutorials from beginner to advanced quality. React provides a JavaScript tutorial for MDN learners.

Read for free online: zh.javascript.info


Scan the QR code below and follow the wechat public account “Technology Chat” to subscribe for more exciting content.