Operation element

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. They are sometimes referred to as “parameters” rather than “operands”.

  • An operator is unary if it corresponds to only one operator; Two are binary operators; Three of them are ternary operators (also called ternary operators).

Arithmetic operators

1. Operation rules

  • I have a Number on the left and a Number on the right

    • The left and right are values, and carry out normal addition, subtraction, multiplication and division modular operations (divisor cannot be 0);
    • NaN on either side, the result returns NaN;
    • Returns the dividend if the dividend is finite and the divisor is infinite:console.log(2 % Infinity); / / 2
    // The divisor cannot be 0
    console.log(10 / 0); // Infinity
    console.log(0 / 0); // NaN
    // The divisor is 0, and NaN is returned
    console.log(10 % 0); // NaN
    console.log(0 % 0); // NaN
    Copy the code
  • If one side is not of Number type, it is converted to Number(Number()) before calculation.

    • Number(null) is 0, Number(undefined) is NaN.

2, addition, subtraction, multiplication and division to power

  • The additive operator
    • add+
    • subtraction-
  • Multiplicative operator
    • The multiplication*
    • division/
    • Mod (mod)%
  • Exponential operator
    • exponentiation六四屠杀, i.e.,Math.pow()

The first four are easy, while % and ** need to be said.

Take more than 2.1%

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

console.log( 5 % 2 ); // the remainder of 5 divided by 2
console.log( 8 % 3 ); // 2, remainder of 8 divided by 3
Copy the code

2.2 exponentiation六四屠杀

Exponentiation a * b is a times itself b times.

In mathematics, the definition of exponentiation also applies to non-integers.

console.log( 4* * (1/2));// 2 (the same thing as the square root)
console.log( 8* * (1/3));// 2 (1/3 power is the same as cube root)
console.log(Math.pow(3.2); // 9 (square root of 3)
console.log(3* *2); // 9 (square root of 3)
Copy the code

2.3 +Connection string (binary)

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";
console.log(s); // mystring

console.log(2 + 2 + '1' ); // The '41' operator works sequentially. That's the same thing as 2 plus 2 plus '1'.
Copy the code

2.4 +Converting numbers (one yuan)

If the operand is not a number, the plus sign + converts it to a number. It has the same effect as Number(), but is shorter.

let s1 = "01";
console.log(+s1); / / 1
console.log( +true ); / / 1
console.log( +"" );   / / 0
Copy the code

2.5 Increase and Decrease (one yuan)

Increment ++ adds the variable to 1; Decrement – subtract a variable from 1;

let counter = 2;
counter++; // same as counter = counter + 1
counter--; // same as counter = counter - 1
Copy the code

Increment/decrement can only be applied to variables.

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

  • Pre-type: use the increment value (new value);
  • Post-type: Uses the pre-increment value (old value).
// increment decrement
let num1 = 0;
let num2 = 0;
let result1 = ++num1 + 2; / / 3
let result2 = num2++ + 2; / / 2
console.log(num2); // 1 post-type: perform the operation first, then increment/decrement. But when you do that, it's going to add to itself.
Copy the code

Shorthand: The pre-operator returns the new value, the post-operator returns the old value.

Relational operators

  • Greater/less than:a > b.a < b.
  • Greater than or equal to/less than or equal to:a >= b.a <= b.
  • Check the equality of two values:a == b.
  • Check that two values are not equal:a ! = b.
  • Check two valuesCongruence (consistent value and type):a === b.
  • Check for two values that are not congruent (at least one of the values is inconsistent with the type) :a ! == b.

All comparison operators return a Boolean value (true or false), and the result of the comparison can be assigned to any variable.

1. Equality rule

  • Left and rightNumberType of
    • The left and right are values, and the values are compared.
    • NaNNot equal to any value, including itself, returnsfalse;
  • One side is notNumberType of
    • Both sides are Object types to compare whether the addresses are the same.
    • null == undefinedreturntrueundefinedDerived fromnullBut of a different type:typeof nullobject.typeof undefinedundefined);
    • One side isStringOn one side, isNumberThat will beStringtoNaNCompare, returnNaN ;
    • One side isNumberOn one side, isTrue, false, undefined, null, toNumberTo compare the.
      • Pay attention tonull == 0falseBecause thenullOnly withundefinedThe same.

2. String comparison

Strings are compared character by character in Unicode encoding order until all characters of a string are compared. If two strings run out of characters at the same time, they are judged equal, otherwise the unended (and uncompared) string is larger.

console.log( 'Z' > 'A' ); // true
console.log( 'A' > 'a' ); // false
console.log( 'Glow' > 'Glee' ); // true
console.log( 'Bee' > 'Be' ); // true
Copy the code

3,nullundefinedTo compare the

  • When using strict equality= = =When comparing the two, they are not equal because they are of different types (typeof nullobject.typeof undefinedundefined).
console.log( null= = =undefined ); // false
Copy the code
  • JavaScript has a special rule that says they are equal null == undefined (undefined derived from NULL) when comparing the two using non-strict equality ==.
console.log( null= =undefined ); // true
Copy the code
  • When using mathematical formulas or other methods of comparison< > < = > =When:

Null /undefined is converted to a number: null is converted to 0, and undefined is converted to NaN.

4. Equality checking and ordinary comparators

  • When ordinary comparators compare values, the comparison value is converted to a number.
  • The equality check == does not perform any type conversions.

4.1 null

console.log( null > 0 );  // (0 > 0 => false)
console.log( null= =0 ); // (2) false (null == 0 => false)
console.log( null> =0 ); // (3) true (0 >= 0 => true)
Copy the code

Yes, the above result completely blows your mind about math. In the case that the last line says “null greater than or equal to zero”, one of the first two lines must be correct, but it turns out that they both result in false.

The reason for this anomalous result is that the code logic for the equality check == and the plain comparator > < >= <= is separate. When ordinary comparators compare values, NULL is converted to a number, so it is converted to 0. This is why null >= 0 in (3) returns true and null > 0 in (1) returns false.

On the other hand, undefined and null do not perform any type conversion in the equality check ==. They have their own independent comparison rules, so they are not equal to anything other than each other. This explains why null == 0 in (2) returns false.

4.2 undefined

console.log( undefined > 0 ); // false (1)
console.log( undefined < 0 ); // false (2)
console.log( undefined= =0 ); // false (3)
Copy the code
  • Both (1) and (2) return false because undefined is converted to NaN in the comparison, and NaN is a special numeric value that returns false when compared with any value.
  • (3) Return false because this is an equality check, and undefined is only equal to null, not other values.

4.3 Avoiding Problems

  • In addition to strict equality= = =Outside, the others but all haveundefined/nullWe all need to be careful about participating in the comparison.
  • Never use unless you know exactly what you’re doing> = > < < =To compare a possiblenull/undefinedThe variables. It could be for the valuesnull/undefined, please check its value separately as needed.

4. Assignment operators

The assignment operator = returns a value.

let a = 1;
let b = 2;

let c = 3 - (a = b + 1); // Useful, but not readable

console.log( a ); / / 3
console.log( c ); / / 0
Copy the code

1. Chain assignment

Chain assignment evaluates from right to left.

let a, b, c;

a = b = c = 2 + 2;

console.log( a, b, c ); / / 4 4 4
Copy the code

2. Modify in situ

We often need to perform an operation on a variable and store the new result in the same variable.

All arithmetic and bitwise operators have short “modify and assign” operators: +=, -=, /=, *=, %=, **=, and so on.

Operators of this class have the same precedence as the normal assignment operator, so they execute after most other operations:

let n = 2;
n *= 3 + 5;
console.log( n ); // 16 (the right-hand part is calculated first, equivalent to n *= 8)
Copy the code

Logical operators

There are three logical operators: logical non (!) , logic and (&) and logic or (| |).

  • &&: Logic and. Returns when both operands are truetrueOtherwise returnfalse.

    • And returns the first false value, or the last value as the result of the operation if there is no false value
    console.log( 1 && 2 && null && 3 ); // null
    console.log( 1 && 2 && 3 ); // 3, the last value
    Copy the code
  • ||: Logical or. Unless both operands arefalseOtherwise, the results are returnedtrue.

    • The or operation returns the first true value, or the last value if both are false
    console.log( null || 1 ); // 1 (1 is the first truth value)
    console.log( null || 0 || 1 ); // 1 (first true value)
    console.log( undefined || null || 0 ); // 0 (all false, return last value)
    Copy the code

Short circuit is evaluated

The and logic or the short-circuit operator will never evaluate the second operand if the first operand determines the result.

Using this feature, you can avoid assigning a variable to null or undefined (setting the default value). For example the let myObject = preferredObject | | backupObject;

  • PreferredObject is the preferred value and backupObject is the standby value.
  • If preferredObjectnull, its value is assigned to the variable; If preferredObject asnull, the value of backupObject is assigned to the variable.
  • !: Logical non. Inversely, applies to only one operand, resulting in a Boolean value.

    • The operand forObjectTo return tofalseAll objects are true);
    console.log( !true ); // false
    console.log( !0 ); // true
    console.log( !{}) ; // false
    Copy the code
    • !!!!!: Double non. The equivalent ofBoolean(), which is used toConverts a value to a Boolean type. The first one!Convert operands to Booleans, second!Invert.
    console.log( !!"non-empty string" ); // true
    console.log( !!null ); // false
    Copy the code

Expressions that can be converted to false are: empty string, NaN, 0, null, or undefined

Null value merge operator??

In JavaScript, we call an expression “defined” if its value is neither null nor undefined.

If the first argument is notnull/undefined,??Returns the first argument. Otherwise, return the second argument.

Null-value merge operators are nothing new. It’s just a nice syntax for getting the first “defined” value of both.

We can rewrite result = a?? Using operators we already know. B, like this:

result = (a ! = =null&& a ! = =undefined)? a : b;Copy the code

Usage Scenarios:

  • Provide a default value for variables that may be undefined.
let user;
// ... 
console.log(user ?? "Anonymous"); // (return the value of user if user has a value, otherwise return 'Anonymous')
Copy the code
  • Select the first non-null /undefined value from a list of values.
let firstName = null;
let lastName = null;
let nickName = "Supercoder";

// Display the first defined value:
console.log(firstName ?? lastName ?? nickName ?? "Anonymous"); // Supercoder
Copy the code

with||To compare

In the code above, we can use the | | replace?? , the same result can also be obtained:

let firstName = null;
let lastName = null;
let nickName = "Supercoder";

// Display the first true value:
console.log(firstName || lastName || nickName || "Anonymous"); // Supercoder
Copy the code

Since the birth of JavaScript is | | operators, so developers to be used for this purpose for a long time.

On the other hand, the null-value merge operator?? Was only recently added to the JavaScript, it is because people for | |.

The important differences are:

  • | | return the first true value.
  • ?? Returns the first defined value.

In other words, | | can’t distinguish between false, 0, an empty string “” and null/undefined. They are all the same — falsy values. If any one is | | the first parameter, then we will get the second parameter as a result.

In practice, we might just want to use the default value when the value of the variable is NULL /undefined.

let height = 0;

console.log(height || 100); / / 100
console.log(height ?? 100); / / 0
Copy the code
  • height || 100It first checks to see if height is a false value and finds that it is. So, the result is the second parameter, 100.
  • height ?? 100First check if height is null/undefined and find that it is not. So, this is the original value of height, 0.

If height 0 is valid, it should not be replaced with the default, so?? You get the right result.

priority

?? The operator has a fairly low priority: 5 in MDN tables. Therefore,?????? In = and? Evaluates before, but after most other operators (for example, + and *).

So, if we need to use?? In expressions with other operators?? To evaluate, consider parentheses:

let height = null;
let width = null;

// Important: use parentheses
let area = (height ?? 100) * (width ?? 50);
// No parentheses
// let area = height ?? 100 * width ?? 50;

console.log(area); / / 5000
Copy the code

??&&||Used together

For security reasons, JavaScript disallows?? Operator with && and | | operators are used together, unless you use parentheses to specify the priority. To avoid people from | | to switch to?? A programming error occurred when.

let x = 1 && 2 ?? 3; // Syntax error
let x = (1 && 2)??3; // ok
Copy the code

7. Optional chain? .

The optional chain operator (? .) allows you to read the value of a property located deep in the chain of connected objects without explicitly validating that each reference in the chain is valid.

? The. Operator functions like the. Chain operator, except that it does not raise an error if the reference is null (or undefined) and returns undefined. When used with a function call, returns undefined if the given function does not exist.

When exploring the contents of an object, the optional chain operator can be helpful if it is not certain which attributes must exist.

const adventurer = {
  cat: {
    name: 'Dinah'}};console.log(adventurer.dog? .name);// undefined
console.log(adventurer.cat? .name);// 'Dinah'

When used with a function call, undefined is returned if the given function does not exist.
console.log(adventurer.someNonExistentMethod? . ());// undefined
Copy the code

Conditional operators? :

Grammar:

let result = condition ? value1 : value2;
Copy the code

Evaluates the conditional result, returning value1 if true, value2 otherwise.

let accessAllowed = (age > 18)?true : false;
Copy the code

Multiple conditional operators can be used consecutively

let age = prompt('age? '.18);

let message = (age < 3)?'Hi, baby! ' :
  (age < 18)?'Hello! ' :
  (age < 100)?'Greetings! ' :
  'What an unusual age! ';

console.log( message );
Copy the code

The comma operator

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.

let a = (1 + 2.3 + 4);
console.log( a ); // 7 (3 + 4)
Copy the code

The comma operator has a very low priority, lower than =, so parentheses are very important in the 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.

Usage scenario: Put several actions on a line for complex computation.

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

Ten bit operators

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 operators are rarely used, usually when we need to manipulate numbers at the lowest level (bits). We won’t be using these operators very quickly because they are rarely used in Web development, but they can be useful in some special areas, such as cryptography. Read the bitwise operators section on MDN when you need to learn more about them.

Operator priority

If an expression has more than one operator, the order of execution is determined by priority.

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 a list of priorities from MDN (you don’t need to remember all of this, but remember that unary operators take precedence over binary operators) :

From high to low:

priority Operation type Correlation between The operator case
21 parentheses N/A (unrelated) (…). 1 plus 2 times 3 // 1 plus 6
20 Member access From left to right … …. And… […]. person1.firstname person1['firstname']
New (with argument list) n/a The new… (…). new Car('Eagle', 1993)
A function call From left to right … (…). myFunc(mycar)
Optional chain From left to right ? . adventurer.dog? .name
19 New (no argument list) From right to left The new… new Car()
18 Postincrement, decrement (operator follows) n/a … + +,… — x++ x--
17 Logic is not From right to left ! … ! true // false
According to a non ~…
Unary addition and subtraction (plus and minus) +… , -… + 1 2 -
Increasing and decreasing in front + +… , -… ++x --x
typeof Typeof… typeof 42 // 'number'
void Void…
delete The delete…
await Await…
16 power From right to left … * *… 2 ** 3 // 8
15 Multiplication, division, modulo From left to right * 、/ 、%
14 Addition, subtraction From left to right +, –
12 Less than … <…
Less than or equal to … < =…
Is greater than … >…
Greater than or equal to … > =…
in … The in…
instanceof … Instanceof…
11 = =,! === =! = =
7 Logic and … &&…
6 Logic or
5 A null value merge … ?? …
4 Conditional operator From right to left … ? … :…
3 The assignment From right to left … =…
… + =…
… – =…
… * * =…
… * =…
… / =…
… % =…
1 Expansion operator n/a . …
0 The comma From left to right … ,…