Equality notation and strict equality notation for Javascript study notes

  • 2020-03-30 04:24:06
  • OfStack

Javascript has two ways to determine if two values are equal.

Equal sign

The equality sign consists of two equal signs: ==
Javascript is a weakly typed language. This means that the equality symbol will be cast in order to compare two values.


""           ==   "0"           // false
0            ==   ""            // true
0            ==   "0"           // true
false        ==   "false"       // false
false        ==   "0"           // true
false        ==   undefined     // false
false        ==   null          // false
null         ==   undefined     // true
" trn"    ==   0             // true

The code above shows the result of the cast, so we know that using the equality symbol == is a bad programming habit. Due to the complex type conversion mechanism in Javascript, the resulting errors can be difficult to trace.
In addition, type casts can have a performance impact, for example, when a string is compared to a number, it is cast to a number.

Strict equality sign

The strict equality sign consists of three equal signs: ===
It is similar to the operation of equality sign, but strict equality sign does not do the type casting operation.


""           ===   "0"           // false
0            ===   ""            // false
0            ===   "0"           // false
false        ===   "false"       // false
false        ===   "0"           // false
false        ===   undefined     // false
false        ===   null          // false
null         ===   undefined     // false
" trn"    ===   0             // false

The code above makes the code clearer and returns false directly if the two values are of different types, which also improves performance.

Comparison of object

Although == and === are known as equality symbols, they behave quite differently when one of the two values being compared is of type object.


{} === {};                   // false
new String('foo') === 'foo'; // false
new Number(10) === 10;       // false
var foo = {};
foo === foo;                 // true

Here, instead of just comparing two values for equality, it will determine whether two values refer to the same object instance, which behaves more like a pointer in C.

conclusion

It is strongly recommended to use only the strict equality symbol ===. If we need to do a cast, we can do an explicit cast before comparing, rather than relying on the complex cast methods of Javascript itself.


Related articles: