Chapter three Language foundation

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

Today we’ll focus on unary operators and Boolean operators, which are used more often than any other programmer. In some of our interviews, Boolean operation judgment is often appear, so new students must seriously knock over the code, remember clearly, don’t be confused.

3.5 the operator

Ecma-262 describes a set of operators that can be used to manipulate data values, including mathematical operators (such as addition and subtraction), bitwise operators, relational operators, and equality operators. Operators in ECMAScript are unique because they can be used for a variety of values, including strings, numeric values, Bools, and even objects. When applied to objects, operators typically call valueOf() and/or toString() methods to get computable values.

3.5.1 Unary operators

Operators that operate on only one value are called unary operators. The unary operator is the simplest operator in ECMAScript.

1. Increment/decrement operators

The increment and decrement operators are directly copied from C, but come in two versions: prefix and suffix. As the name implies, the prefix version precedes the variable to be manipulated, and the suffix version precedes the variable to be manipulated. The prefix increment operator increments the value by one by placing two plus signs (++) before the variable:

let age = 29; 
++age;
Copy the code

In this example, the prefix increment operator changes the age value to 30 (adding 1 to the previous value of 29). Therefore, it is actually equal to the following expression:

let age = 29; 
age = age + 1;
Copy the code

The prefix decrement operator is similar, except that it subtracts 1 from a number. To use the prefix decrement operator, simply place two minus signs (–) before the variable:

let age = 29; 
--age; 
Copy the code

After the operation, the value of the age variable becomes 28 (minus 1 from 29). Whether the prefix increment or prefix decrement operators are used, the value of the variable changes before the statement is evaluated. (In computer science, this is often called having a side effect.) Look at the following example:

let age = 29; let anotherAge = --age + 2; console.log(age); // 28 console.log(anotherAge); / / 30Copy the code

In this example, the variable anotherAge is initialized with the value of age minus 1 plus 2. Because decrement happens first, the age value becomes 28 and then increases by 2, resulting in 30. Prefix increment and decrement have equal precedence in a statement and are therefore evaluated from left to right. Such as:

let num1 = 2; let num2 = 20; let num3 = --num1 + num2; let num4 = num1 + num2; console.log(num3); // 21 console.log(num4); / / 21Copy the code

Here, num3 equals 21 because num1 is subtracted by 1 before num2 is added. The variable num4 is also 21, because addition also uses the decrement value. Incrementing and decrementing have the same postfix syntax (++ and –, respectively), but after variables. The main difference between the suffix version and the prefix version is that the increment and decrement of the suffix version does not occur until the statement has been evaluated. In some cases, the difference doesn’t matter, such as:

let age = 29; 
age++; 
Copy the code

Placing an increment operator after a variable does not change the result of statement execution because increment is the only operation. However, when mixed with other exercises, the differences become apparent, such as:

let num1 = 2; let num2 = 20; let num3 = num1-- + num2; let num4 = num1 + num2; console.log(num3); // 22 console.log(num4); / / 21Copy the code

This example is the same as the previous one, except that the prefix decrement is changed to the suffix decrement, the difference is obvious. In the example using the prefix version, num3 and num4 both have the value 21. In this case, num3 is 22 and num4 is 21. The difference here is that num3 is computed using the original num1 value (2), while NUM4 is computed using the decrement num1 value (1).

These four operators can work on any value, meaning that they are not limited to integers — strings, Bools, floating-point values, and even objects. The increment and decrement operators follow these rules.

  • For a string, if it is a valid numeric form, convert it to a numeric value and apply the change. The variable type changes from a string to a number
  • For strings, 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 number.
  • For Boolean values, if false, convert to 0 and apply the change. The variable type changes from a Boolean to a numeric value.
  • For booleans, if true, convert to 1 and apply the change. The variable type changes from a Boolean to a numeric value.
  • For floating-point values, add or subtract 1.
  • If it is an object, the valueOf() method (described in more detail in Chapter 5) is called to get a value that can be manipulated. Apply the above rules to the resulting values. In the case of NaN, toString() is called and the other rules are applied again. The variable type changes from object to value.

The following example illustrates these rules

let s1 = "2"; let s2 = "z"; let b = false; Let f = 1.1; let o = { valueOf() { return -1; }}; s1++; // The value becomes the number 3 s2++; // the value becomes NaN b++; // The value becomes the value 1 f--; // The value becomes 0.10000000000000009 (because floating point numbers are imprecise) o--; // The value becomes -2Copy the code

2. Unary plus and minus

Unary plus and minus operators are familiar to most developers; they are used in ECMAScript the same way they are used in high school math. Unary addition is indicated by a plus sign (+) placed before the variable and has no effect on the value:

let num = 25; num = +num; console.log(num); / / 25Copy the code

If unary addition is applied to a non-numeric value, the same type conversion is performed as with the Number() conversion function: Boolean values false and true are converted to 0 and 1, strings are parsed according to special rules, and objects call their valueOf() and/or toString() methods to get values that can be converted.

The following example demonstrates the behavior of unary addition when applied to different data types:

let s1 = "01"; Let s2 = "1.1"; let s3 = "z"; let b = false; Let f = 1.1; let o = { valueOf() { return -1; }}; s1 = +s1; S2 = +s2; S3 = +s3; // The value becomes NaN b = +b; // Change the value to 0 f = +f; // same as 1.1o = +o; // The value becomes the value -1Copy the code

Unary subtraction, indicated by a minus sign (-), precedes a variable and is mainly used to change a value into a negative value, such as from 1 to -1. The following is an example:

let num = 25; num = -num; console.log(num); / / to 25Copy the code

Using unary subtraction on a numeric value turns it into the corresponding negative value (as shown in the example above). When applied to non-values, unary subtraction follows the same rules as unary addition, converting them first and then taking negative values:

let s1 = "01"; Let s2 = "1.1"; let s3 = "z"; let b = false; Let f = 1.1; let o = { valueOf() { return -1; }}; s1 = -s1; // the value becomes the value -1 s2 = -s2; // the value becomes a value -1.1 s3 = -s3; // The value becomes NaN b = -b; // Change the value to 0 f = -f; // change to -1.1o = -o; // The value becomes 1Copy the code

The unary addition and subtraction operators are primarily used for basic arithmetic, but can also be used for data type conversions, as in the example above.

3.5.2 Boolean operators

The Boolean operator is almost as important to a programming language as the equality operator. Statements like if-else and loops are useless without the ability to test the relationship between two values. There are three Boolean operators: logical not, logical and logical or.

1. The logic

Logical non-operators consist of an exclamation mark (!). Can be applied to any value in ECMAScript. This operator always returns a Boolean, regardless of the data type being applied. A logical nonoperator first converts the operand to a Boolean value and then inverts it. In other words, logical non-operators follow the following rules.

  • Return false if the operand is an object.
  • Returns true if the operand is an empty string.
  • Return false if the operand is a non-empty string.
  • Returns true if the operand is the value 0.
  • Return false if the operand is a non-zero value (including Infinity).
  • If the operand is null, true is returned.
  • Returns true if the operand is NaN.
  • Returns true if the operand is undefined.

The following example verifies the above behavior:

console.log(! false); // true console.log(!" blue"); // false console.log(! 0); // true console.log(! NaN); // true console.log(!" "); // true console.log(! 12345); // falseCopy the code

Logical nonoperators can also be used to convert arbitrary values to Boolean values. Use two exclamation points (!!) at the same time , equivalent to calling the transition function Boolean(). Regardless of the type of operand, the first exclamation mark always returns a Boolean value. The second exclamation mark reverses the Boolean value, giving the true Boolean value of the variable. The result is the same as using the Boolean() function on the same value:

console.log(!!" blue"); // true console.log(!! 0); // false console.log(!! NaN); // false console.log(!!" "); // false console.log(!! 12345); // trueCopy the code

2. Logic and

The logic and operators are represented by two ampersand signs (&&) and apply to two values, as shown below

let result = true && false;
Copy the code

The logic and operators follow the following truth table:

The first operand Second operand Bear fruit
true true false
true false false
false true false
false false false

Logic and operators can be used for any type of operands, not just booleans. If an operand is not a Boolean, the logical sum does not necessarily return a Boolean, but follows the following rule.

  • If the first operand is an object, return the second operand.
  • If the second operand is an object, the object is returned only if the first operand evaluates to true.
  • If both operands are objects, return the second operand.
  • If one of the operands is NULL, null is returned.
  • NaN is returned if one of the operands is NaN.
  • Returns undefined if one of the operands is undefined.

The logical and operator is a short-circuit operator, meaning that if the first operand determines the result, the second operand is never evaluated. For logic and operators, if the first operand is false, the result cannot be true regardless of the value of the second operand. Look at the following example:

let found = true; let result = (found && someUndeclaredVariable); Console. log(result); // This line will not be executedCopy the code

The above code fails because someUndeclaredVariable is not declared beforehand, so an error is reported when the logic and operator evaluate it. The value of the variable found is true, and the logic and operator will continue to evaluate the variable someUndeclaredVariable. SomeUndeclaredVariable is not defined, so you cannot apply logic and operators to it. If the variable found has the value false, then the error will not be reported:

let found = false; let result = (found && someUndeclaredVariable); Console. log(result); / /Copy the code

Here, console.log will execute successfully. Even if the variable someUndeclaredVariable is not defined, since the first operand is false, the logic and operator will not evaluate it, because it makes no sense to evaluate the operand to the right of &&. When using logic and operators, it is important to remember this short-circuit property.

3. The logical or

Logic or the operator by two pipe (| |) said, such as:

let result = true || false;
Copy the code

The logic or operators follow the following truth table:

The first operand Second operand Bear fruit
true true true
true false true
false true true
false false false

Similar to logic, if an operand is not a Boolean, the logic or operator does not necessarily return a Boolean. It follows the following rules.

  • Returns the first operand if the first operand is an object.
  • If the first operand evaluates to false, the second operand is returned.
  • If both operands are objects, return the first operand.
  • If both operands are null, null is returned.
  • If both operands are NaN, NaN is returned.
  • If both operands are undefined, undefined is returned.

Similarly to logic, logic or operators have the property of short-circuiting. Only for logic, if the first operand evaluates to true, the second operand will not be evaluated. Look at the following example:

let found = true; let result = (found || someUndeclaredVariable); Console. log(result); / /Copy the code

As in the previous example, the variable someUndeclaredVariable is not defined. However, because the variable found has a value of true, the logic or operator does not evaluate the variable someUndeclaredVariable, but simply returns true. If you change the value of found to false, you will get an error:

let found = false; let result = (found || someUndeclaredVariable); Console. log(result); // This line will not be executedCopy the code

Using this behavior, you can avoid assigning a variable to null or undefined. Such as:

let myObject = preferredObject || backupObject; 
Copy the code

In this example, the variable myObject is given one of two values. The preferredObject variable contains the first-selected value, and the backupObject variable contains the alternate value. If the preferredObject is not null, its value is assigned to myObject; If the preferredObject is null, the value of backupObject is assigned to myObject. This schema is often used for variable assignments in ECMAScript code and will be used in subsequent code examples.