Chapter three Language foundation

This is the 9th day of my participation in the August More Text Challenge

Today we continue to talk about operators, it is these basic knowledge that built the building of JavaScript, I have always felt that the difficulty of programming is the variety, so many permutations of knowledge, we have to do is to use the most appropriate method in the most appropriate place. All kinds of frameworks, including those to be learned later, are assembled on the basis of the original. Only by understanding the knowledge at the bottom can we give full play to the advantages of programming.

3.5.4 Multiplicative operator

ECMAScript defines three multiplication operators: multiplication, division, and modulo. These operators do what their Java, C, and Perl counterparts do, but they also include some automatic type conversions for non-numeric values. If the multiplicative operator has an operand that is not a Number, that operand is converted to a Number behind the scenes using the Number() transformation function. This means that the empty string is treated as a 0, and the Boolean true is treated as a 1.

1. Multiplication operator

The multiplication operator is represented by an asterisk (*) and can be used to compute the product of two numeric values. The syntax is similar to that of C, for example:

let result = 34 * 56; 
Copy the code

However, the multiplication operator also has some special behavior when dealing with special values.

  • If the operands are all numeric, then the normal multiplication is performed, that is, two positive values multiplied together are positive, two negative values multiplied together are positive, and values with different signs are multiplied together to produce negative values. If ECMAScript cannot represent a product, Infinity or -infinity is returned.
  • NaN is returned if any of the operands is NaN. 3.5 Operators 67 8 12 3 4 5 14 67 9 10 11 13 12
  • If it’s Infinity times 0, NaN is returned.
  • If Infinity is multiplied by a finite number that is not zero, Infinity or -infinity is returned based on the sign of the second operand.
  • If it’s Infinity times Infinity, it returns Infinity.
  • If you have an operand that is not a value, you convert it to a value behind the scenes with Number() before applying the above rules.

2. The division operator

The division operator, represented by a slash (/), calculates the quotient of the first operand divided by the second operand, as in:

let result = 66 / 11;
Copy the code

Like the multiplication operator, the division operator has some special behavior for special values.

  • If the operands are both numerical, the conventional division is performed, that is, two positive values divided by two negative values are positive, and values with different signs divided by each other are negative. If ECMAScript cannot represent quotient, Infinity or -infinity is returned.
  • NaN is returned if any of the operands is NaN.
  • If it’s Infinity divided by Infinity, it returns NaN.
  • If it’s 0 divided by 0, NaN is returned.
  • If a nonzero finite value is divided by 0, Infinity or -infinity is returned based on the sign of the first operand.
  • If Infinity is divided by any number, Infinity or -infinity is returned based on the sign of the second operand.
  • If you have an operand that is not a Number, you convert it to a Number behind the scenes using the Number() function before applying the above rules.

3. Fetch operator

The modulo (remainder) operator is represented by a percentage sign (%), such as:

let result = 26 % 5; / / equal to 1Copy the code

Like other multiplicative operators, the modulo operator has some special behavior for special values.

  • If the operand is numeric, a normal division operation is performed, returning the remainder.
  • If the dividend is infinite and the divisor is finite, NaN is returned.
  • If the dividend is finite and the divisor is 0, NaN is returned.
  • If it’s Infinity divided by Infinity, it returns NaN.
  • Returns the dividend if the dividend is finite and the divisor is infinite.
  • If the dividend is 0 and the divisor is not 0, 0 is returned.
  • If you have an operand that is not a Number, you convert it to a Number behind the scenes using the Number() function before applying the above rules.

3.5.5 Exponential operators

ECMAScript 7 adds the index operator, math.pow () now has its own operator **, the result is the same:

console.log(Math.pow(3, 2); // 9 console.log(3 ** 2); / / 9 console. The log (math.h pow (16, 0.5); / / 4 console. The log (16 * * 0.5); / / 4Copy the code

In addition, the index operator also has its own index assignment operator **=, which performs the index and result assignment:

let squared = 3; squared **= 2; console.log(squared); // 9 let sqrt = 16; SQRT * * = 0.5; console.log(sqrt); / / 4Copy the code

3.5.6 Additive operators

The additive operators, the addition and subtraction operators, are generally the simplest operators in a programming language. However, in ECMAScript, these two operators have some special behavior. Like the multiplicative operator, the additive operator performs conversions of different data types behind the scenes. It’s just that the conversion rules are not so straightforward for these two operators.

1. Add operator

The addition operator (+) is used to find the sum of two numbers, as in:

let result = 1 + 2;
Copy the code

If both operands are numeric, the addition operator performs addition and returns the result according to the following rules:

  • NaN is returned if any of the operands is NaN;
  • If Infinity plus Infinity, Infinity is returned;
  • If it’s -infinity plus -infinity, it returns -infinity;
  • If Infinity plus -infinity, NaN is returned;
  • If it is +0 +0, it returns +0;
  • If it is -0 plus +0, +0 is returned;
  • If it’s -0 plus -0, it returns -0.

However, if one of the operands is a string, the following rule applies:

  • If both operands are strings, concatenate the second string to the first;
  • If only one operand is a string, the other operand is converted to a string and the two strings are concatenated.

If any of the operands are objects, values, or booleans, their toString() method is called to get the string, and the previous string rules apply. For undefined and null, the String() function is called to get “undefined” and “null”, respectively.

Look at the following example:

let result1 = 5 + 5; // Two values console.log(result1); // 10 let result2 = 5 + "5"; // A number and a string console.log(result2); / / "55"Copy the code

The above code shows two modes of operation for the addition operator. Normally, 5 + 5 equals 10 (numeric), as shown in the first two lines of code. However, if you change an operand to a string, such as “5”, the result of the addition becomes “55” (the original string value) because the first operand is also converted to a string.

One of the most common mistakes made in ECMAScript is to ignore data types involved in addition operations. Take this example:

let num1 = 5; 
let num2 = 10; 
let message = "The sum of 5 and 10 is " + num1 + num2; 
console.log(message); // "The sum of 5 and 10 is 510" 
​
Copy the code

In this case, the variable message holds a string, the result of two addition operations. One might think that The resulting string would be “The sum of 5 and 10 is 15”. “The sum of 5 and 10 is 510”. This is because each addition is done independently. The operand of the first addition is a string and a number (5), and the result is still a string. The second addition is still adding a number (10) to a string, which also yields a string. If you want to actually do the math and then append the result to the end of the string, just use a pair of parentheses:

let num1 = 5; 
let num2 = 10; 
let message = "The sum of 5 and 10 is " + (num1 + num2); 
console.log(message); // "The sum of 5 and 10 is 15" 
Copy the code

Here, we enclose the two numeric variables in parentheses, which means that the interpreter performs the addition of the two values before appending the result to the string. Therefore, The resulting string becomes “The sum of 5 and 10 is 15”.

2. Subtraction operators

The subtraction operator (-) is also a frequently used operator, such as:

let result = 2 - 1; 
Copy the code

Like the addition operator, the subtraction operator has a set of rules for handling conversions between different types in ECMAScript.

If both operands are numeric, mathematical subtraction is performed and the result is returned.

  • NaN is returned if any of the operands is NaN.
  • If Infinity minus Infinity, NaN is returned.
  • If it is -infinity minus -infinity, NaN is returned.
  • If it’s Infinity minus -infinity, it returns Infinity.
  • If it’s -infinity minus Infinity, it returns -infinity.
  • If it’s +0 minus +0, it returns +0.  Returns -0 if it is +0 minus -0.
  • If it’s -0 minus -0, it returns +0.
  • If any of the operands is a string, Boolean, null, or undefined, it is first converted to a numeric value behind the scenes using Number(), and then the math is performed according to the previous rules. If the result of the transformation is NaN, the result of the subtraction calculation is NaN.
  • If any of the operands is an object, the valueOf() method is called to get the value representing it. If the value is NaN, the result of the subtraction calculation is NaN. If the object does not have a valueOf() method, its toString() method is called and the resulting string is then converted to a value.

The following example demonstrates the above rule:

let result1 = 5 - true; // true is converted to 1, so the result is 4. // NaN let result3 = 5 - 3; // 2 let result4 = 5 - ""; Let result5 = 5 - "2"; // let result6 = 5 - null; // null is converted to 0, so the result is 5Copy the code

3.5.7 Relational operators

The relational operator performs the comparison of two values, including less than (<), greater than (>), less than or equal to (<=), and greater than or equal to (>=), as we learned in math class. Each of these operators returns a Boolean value, as shown below:

let result1 = 5 > 3; // true 
let result2 = 5 < 3; // false 
​
Copy the code

Like other operators in ECMAScript, type conversions and other behaviors occur when they are applied to different data types.

  • If the operands are all numeric, a numeric comparison is performed.
  • If the operands are all strings, the encoding of the corresponding character in the string is compared one by one.
  • If any of the operands is a value, the other operand is converted to a value and a numeric comparison is performed.
  • If any of the operands are objects, the valueOf() method is called, and the comparison is performed according to the previous rules after the result is obtained. If there is no valueOf() operator, the toString() method is called and the comparison is performed according to the previous rules after the result is obtained.
  • If any of the operands is a Boolean, it is converted to a numeric value before the comparison is performed.

An interesting phenomenon occurs when two strings are compared using the relational operator. Many people think that less means “alphabetically forward” and greater means “alphabetically backward,” but that’s not the case. In the case of strings, relational operators compare the encoding of the corresponding characters in the string, which are numeric values. After the comparison, a Boolean value is returned. The point is that the encoding of uppercase letters is smaller than that of lowercase letters, so something like this can happen:

let result = "Brick" < "alphabet"; // true
Copy the code

Here, the string “Brick” is considered less than the string “alphabet” because the code of the letter B is 66 and the code of the letter A is 97. To get a true alphabetical comparison, you must convert both to the same case (all uppercase or all lowercase) and then compare:

let result = "Brick".toLowerCase() < "alphabet".toLowerCase(); // false 
Copy the code

Converting both operands to lowercase ensures that “alphabet” precedes “Brick” in alphabetical order. Another strange phenomenon occurs when comparing two numeric strings, as in the following example:

let result = "23" < "3"; // true 
Copy the code

This returns true when comparing the strings “23” and “3”. Because both operands are strings, their character encodings are compared one by one (the encoding for character “2” is 50, and the encoding for character “3” is 51). However, if one of the operands is numeric, then the comparison is correct:

let result = "23" < 3; // false
Copy the code

Because this time I’m going to convert the string “23” to the number 23, and then I’m going to compare it to 3, and of course I’m going to get the right answer. Whenever a numeric value is compared to a string, the string is converted to a numeric value and then compared to a numeric value. For numeric strings, this ensures that the result is correct. But what if strings can’t be converted to numbers? Take this example:

let result = "a" < 3; // Since "a" is converted to NaN, the result is falseCopy the code

Because the character “a” cannot be converted to any meaningful value, it can only be converted to NaN. There is a rule that any relational operator returns false when it involves comparing NaN. This makes the following example interesting:

let result1 = NaN < 3; // false 
let result2 = NaN >= 3; // false 
Copy the code

In most comparison scenarios, if one value is not less than another, it must be greater than or equal to it. But when comparing nans, whether less than or greater than or equal to, the result of the comparison returns false.

3.5.8 Equality operator

Determining whether two variables are equal is one of the most important operations in programming. The procedure is straightforward when comparing whether strings, values, and Boilervalues are equal. But when comparing two objects for equality, the situation becomes more complicated. The equality and inequality operators in ECMAScript originally performed type conversions before comparisons, but it was quickly questioned whether such conversions should happen at all. Finally, ECMAScript provides two sets of operators. The first group is equal and not equal, and they perform the conversion before the comparison. The second group is congruent and incongruent, which do not perform the conversion before the comparison.

1. Equal and not equal

The ECMAScript equal operator is represented by two equals signs (==) and returns true if the operands are equal. The unequal operator uses an exclamation mark and an equal sign (! =) means that true is returned if the operands are not equal. Both operators perform a row type conversion (often called a cast) to determine whether the operands are equal.

The equality and inequality operators follow the following rules when converting operand types.

  • If any of the operands is a Boolean, it is converted to a value and then compared for equality. False converts to 0 and true converts to 1.
  • If one of the operands is a string and the other is a value, it tries to convert the string to a value and then compares for equality.
  • If one operand is an object and the other is not, the valueOf() method of the object is called to get its original value, which is then compared according to the previous rules. When comparing, the two operators follow the following rules.
  • Null is equal to undefined.
  • Null and undefined cannot be converted to other types of values for comparison.
  • If any of the operands is NaN, the equality operator returns false and the inequality operator returns true. Remember: Even if both operands are NaN, the equality operator returns false because NaN is not equal to NaN by rule.
  • If both operands are objects, they are compared to see if they are the same object. The equality operator returns true if both operands refer to the same object. Otherwise, the two are not equal.

The table below summarizes some special cases and the results of the comparison.

expression Bear fruit
null == undefined true
“NaN” == NaN false
5 == NaN false
NaN == NaN false
NaN ! = NaN true
false == 0 true
true == 1 true
true == 2 false
undefined == 0 false
null == 0 false
“5” = = 5 true

2. Congruence and incongruence

The congruence and incongruence operators are similar to the equality and inequality operators, except that they do not convert operands when comparing equality. Congruent operators are represented by three equals signs (===) and return true only if the two operands are equal without conversion, as in:

let result1 = ("55" == 55); Result2 = ("55" === 55); // false, unequal because of different data typesCopy the code

In this example, the first comparison uses the equality operator and compares the string “55” with the number 55. As mentioned earlier, true is returned because the string “55” is converted to the value 55 and then compared to the value 55. The second comparison uses the congruence operator, which returns false because string and value cannot be equal without conversion.

The incongruent operator uses an exclamation mark and two equals signs (! ==) returns true only if the two operands are not equal without the conversion. Such as:

let result1 = ("55" ! = 55); Result2 = ("55"! = = 55); // true, not equal, because the data type is differentCopy the code

This time, the first comparison uses the unequal operator, which converts the string “55” to the value 55, equal to the second operand. Since the two values are equal after conversion, return false. The second comparison uses the incongruent operator. Ask: “Is there a difference between the string 55 and the number 55?” The answer is true

Also, although null == undefined is true (because the two values are similar), null === undefined is false because they are not of the same data type.

Note that the congruence and incongruence operators are recommended because of type conversion problems with the equality and inequality operators. This helps maintain the integrity of the data types in your code.

3.5.9 Conditional operators

The conditional operator is one of the most widely used operators in ECMAScript and has the same syntax as in Java:

variable = boolean_expression ? true_value : false_value; 
Copy the code

The above code performs conditional assignment, which determines which value to assign to variable based on the value of the conditional boolean_expression. If boolean_expression is true, true_value is assigned; False_value is assigned if boolean_expression is false. Such as:

let max = (num1 > num2) ? num1 : num2;
Copy the code

In this example, Max will be assigned a maximum value. This expression means that if num1 is greater than num2 (conditional table reach is true), num1 is assigned to Max. Otherwise, num2 is assigned to Max.

3.5.10 Assignment operator

Simple assignment is denoted by the equals sign (=), and assigns the value of the right hand side to the variable on the left hand side as follows:

let num = 10; 
Copy the code

Compound assignment is indicated by a multiplicative, additive, or bitwise operator followed by an equals sign (=). These assignment operators are shorthand for common assignment operations like the following:

let num = 10; 
num = num + 10;
Copy the code

The second line of the above code can be done with a compound assignment:

let num = 10; 
num += 10; 
Copy the code

Each mathematical operator, as well as several others, has a corresponding compound assignment operator:

  • Multiply and assign (*=)
  • Assign after division (/=)
  • After modulo assignment (%=)
  • Assign (+=)
  • Assignment after subtraction (-=)
  • Assign after left shift (<<=)
  • Assign after right shift (>>=)
  • Assignment after unsigned right shift (>>>=)

These operators are simply shorthand syntax and using them does not improve performance.

3.5.11 Comma operator

The comma operator can be used to perform multiple operations in a single statement, as follows:

let num1 = 1, num2 = 2, num3 = 3; 
Copy the code

Declaring multiple variables simultaneously in a single statement is the most common scenario for the comma operator. However, you can also use the comma operator to aid assignment. Using the comma operator to separate values in assignment eventually returns the last value in the expression:

let num = (5, 1, 4, 8, 0); // the value of num is 0Copy the code

In this example, num will be assigned 0 because 0 is the last item in the expression. This use of the comma operator is rare, but it does exist.