JS operator - comparison operator

Keywords: Java Javascript html5

Comparison operator

summary

The comparison operator is used to compare the size of two values, and then return a Boolean value indicating whether the specified conditions are met.

2 > 1 // true

The above code compares whether 2 is greater than 1 and returns true.

Note that comparison operators can compare various types of values, not just numeric values.

JavaScript provides a total of eight comparison operators.

  • >Greater than operator
  • < less than operator
  • < = less than or equal to operator
  • >=Greater than or equal to operator
  • ==Equality operator
  • ===Strict equality operator
  • != Unequal operator
  • !== Strict inequality operator

The eight comparison operators are divided into two categories: equal comparison and unequal comparison. The rules of the two are different. For unequal comparison, the algorithm first depends on whether the two operators are strings. If so, compare them in dictionary order (actually comparing Unicode code points); Otherwise, both operators are converted to numerical values, and then the values are compared.

Unequal operator: comparison of strings

Strings are compared in dictionary order.

'cat' > 'dog' // false
'cat' > 'catalog' // false

The JavaScript engine first compares the Unicode code point of the first character. If equal, compare the Unicode code points of the second character, and so on.

'cat' > 'Cat' // true'

In the above code, the Unicode code point (99) of lowercase C is greater than that of uppercase C (67), so it returns true.

Since all characters have Unicode code points, Chinese characters can also be compared.

'large' > 'Small' // false

In the above code, the Unicode code point of "large" is 22823 and "small" is 23567, so false is returned.

Unequal operator: comparison of non strings

If at least one of the two operators is not a string, it needs to be divided into the following two cases.

(1) Original type value

If both operators are values of the original type, they are converted to values before comparison.

5 > '4' // true
// Equivalent to 5 > number ('4 ')
// I.e. 5 > 4

true > false // true
// Equivalent to number (true) > number (false)
// I.e. 1 > 0

2 > true // true
// Equivalent to 2 > number (true)
// I.e. 2 > 1

In the above code, both string and Boolean values will be converted to numeric values before comparison.

Here we need to pay attention to the comparison with NaN. Any value (including NaN itself) compared with NaN using the non equality operator returns false.

1 > NaN // false
1 <= NaN // false
'1' > NaN // false
'1' <= NaN // false
NaN > NaN // false
NaN <= NaN // false

(2) Object

If the operator is an object, it is converted to the value of the original type for comparison.

Object is converted to the value of the original type. The algorithm is to call the valueOf method first; If the returned object is still an object, then call the toString method. See the chapter "data type conversion" for details.

var x = [2];
x > '11' // true
// Equivalent to [2]. Valueof(). Tostring() > '11'
// I.e. '2' > '11'

x.valueOf = function () { return '1' };
x > '11' // false
// Equivalent to [2]. Valueof() > '11'
// I.e. '1' > '11'

The same is true for the comparison between two objects.

[2] > [1] // true
// Equivalent to [2]. Valueof(). Tostring() > [1]. Valueof(). Tostring())
// I.e. '2' > '1'

[2] > [11] // true
// Equivalent to [2]. Valueof(). Tostring() > [11]. Valueof(). Tostring())
// I.e. '2' > '11'

{ x: 2 } >= { x: 1 } // true
// Equivalent to {X: 2}. Valueof(). Tostring() > = {X: 1}. Valueof(). Tostring())
// That is' [object] '> =' [object] '

Strict equality operator

JavaScript provides two equality operators: = = and = = =.

In short, the difference between them is that the equality operator (= =) compares whether two values are equal, and the strict equality operator (= =) compares whether they are "the same value". If two values are not of the same type, the strict equality operator (= =) directly returns false, and the equality operator (= =) converts them to the same type, and then compares them with the strict equality operator.

This section describes the algorithm for the strict equality operator.

(1) Different types of values

If the two values are of different types, return false directly.

1 === "1" // false
true === "true" // false

The above code compares the value 1 with the string "1", and the Boolean value true with the string "true". Because of different types, the result is false.

(2) Original type value of the same class

When comparing the values (numeric value, string, Boolean value) of the original type of the same type, true will be returned if the values are the same, and false if the values are different.

1 === 0x1 // true

The above code compares decimal 1 with hexadecimal 1. Because the type and value are the same, it returns true.

Note that NaN is not equal to any value (including itself). In addition, positive 0 equals negative 0.

NaN === NaN  // false
+0 === -0 // true

(3) Composite type value

When comparing the data of two composite types (objects, arrays, functions), we do not compare whether their values are equal, but whether they point to the same address.

{} === {} // false
[] === [] // false
(function () {} === function () {}) // false

The above code compares two empty objects, two empty arrays and two empty functions respectively, and the results are not equal. The reason is that for the values of composite types, the strict equality operation compares whether they refer to the same memory address, and the values of empty objects, empty arrays and empty functions on both sides of the operator are stored in different memory addresses. Of course, the result is false.

If two variables refer to the same object, they are equal.

var v1 = {};
var v2 = v1;
v1 === v2 // true

Note that for the comparison of two objects, the strict equality operator compares addresses, and the greater than or less than operator compares values.

var obj1 = {};
var obj2 = {};

obj1 > obj2 // false
obj1 < obj2 // false
obj1 === obj2 // false

For the above three comparisons, the first two compare values and the last one compares addresses, so they all return false.

(4) undefined and null

undefined and null are strictly equal to themselves.

undefined === undefined // true
null === null // true

Since the default value after variable declaration is undefined, two variables that only declare unassigned values are equal.

var v1;
var v2;
v1 === v2 // true

Strict inequality operator

The strict equality operator has a corresponding "strict inequality operator" (! = =). Its algorithm is to find the result of the strict equality operator first, and then return the opposite value.

1 !== '1' // true
// Equivalent to
!(1 === '1')

In the above code, exclamation point! Is to find the opposite value of the following expression.

Equality operator

The equality operator is exactly the same as the strict equality operator when it is used to compare data of the same type.

1 == 1.0
// Equivalent to
1 === 1.0

When comparing different types of data, the equality operator will first type convert the data, and then compare it with the strict equality operator. The following is divided into several cases to discuss the rules for comparing different types of values.

(1) Original type value

The value of the original type is converted to a numeric value for comparison.

1 == true // true
// Equivalent to 1 === Number(true)

0 == false // true
// Equivalent to 0 === Number(false)

2 == true // false
// Equivalent to 2 === Number(true)

2 == false // false
// Equivalent to 2 === Number(false)

'true' == true // false
// Equivalent to Number('true') === Number(true)
// Equivalent to NaN === 1

'' == 0 // true
// Equivalent to Number('') === 0
// Equivalent to 0 = = = 0

'' == false  // true
// Equivalent to Number('') === Number(false)
// Equivalent to 0 = = = 0

'1' == true  // true
// Equivalent to Number('1') === Number(true)
// Equivalent to 1 = = = 1

'\n  123  \t' == 123 // true
// Because when a string is converted to a number, the leading and trailing spaces are omitted

The above code converts both string and Boolean values to numeric values, and then compares them. For specific type conversion rules for string and Boolean values, see chapter data type conversion.

(2) Object is compared with the original type value

When an object (here refers to a generalized object, including arrays and functions) is compared with the value of the original type, the object is converted to the value of the original type and then compared.

Specifically, first call the valueOf() method of the object. If you get the values of the original type, compare them with each other according to the rules in the previous section; If you still get an object, call the toString() method to get the string form, and then compare it.

The following is an example of comparing an array with the original type value.

// Comparison of arrays and values
[1] == 1 // true

// Comparison of array and string
[1] == '1' // true
[1, 2] == '1,2' // true

// Object vs. Boolean
[1] == true // true
[2] == true // false

In the above example, the JavaScript engine will first call the valueOf() method of the array on array [1]. Since the returned array is still an array, it will then call the toString() method of the array to obtain the string form, and then compare it according to the rules in the previous section.

Here is a more direct example.

const obj = {
  valueOf: function () {
    console.log('implement valueOf()');
    return obj;
  },
  toString: function () {
    console.log('implement toString()');
    return 'foo';
  }
};

obj == 'foo'
// Execute valueOf()
// Execute toString()
// true

In the above example, obj is an object with customized valueof () and toString () methods. When this object is compared with the string 'foo', it will call valueOf() and toString() methods in turn, and finally return 'foo', so the comparison result is true.

(3) undefined and null

undefined and null will return true only when compared with themselves or with each other; When compared with other types of values, the result is false.

undefined == undefined // true
null == null // true
undefined == null // true

false == null // false
false == undefined // false

0 == null // false
0 == undefined // false

(4) Disadvantages of equality operator

The type conversion hidden by the equality operator will bring some counterintuitive results.

0 == ''             // true
0 == '0'            // true

2 == true           // false
2 == false          // false

false == 'false'    // false
false == '0'        // true

false == undefined  // false
false == null       // false
null == undefined   // true

' \t\r\n ' == 0     // true

These expressions are different from intuition and are easy to make mistakes. Therefore, it is recommended not to use the equality operator (= =), and it is best to use only the strict equality operator (= =).

Unequal operator

The equality operator has a corresponding "unequal operator" (! =), and its algorithm is to find the result of the equality operator first, and then return the opposite value.

1 != '1' // false

// Equivalent to
!(1 == '1')

Posted by klaaz on Wed, 22 Sep 2021 01:08:16 -0700