The difference between == and === in JavaScript

"==" case

1. Two different basic data types: if the two basic data types (string, number) are different, they will be converted into data types, and then compared. For example:

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

false == '0'                                             // true
false == 'false'                                         // false
false == null                                            // false
false == undefined                                       // false
null == undefined                                        // true

0 === ''                                                 // false
0 === '0'                                                // false
1 === '1'                                                // false

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

2. Basic Data Type and Reference Data Type: Transform Reference Data Type (function, object, which includes array) into its original value (background automatically calls `Object.prototype.valueOf()) and compare them. For example:

[1,2] == '0'                                            // true
function(){return ['1,2']}() == '1,2'                   // true

[1,2] === '0'                                           // false
function(){return ['1,2']}() === '1,2'                  // false

3. Two reference types: judging the reference path between them. For example:

[1,2] == [1,2]                                          // false
[1,2] === [1,2]                                         // false

"===" case

As can be seen from the above examples, without type conversion, different types must return to fasle.

Summary: Recommended use "===", as long as the type is inconsistent, return to fasle directly; "==" will cause type conversion and comparison, not rigorous.

Original address: https://www.artroy.com.cn/art...
More articles to share: https://www.artroy.com.cn/

Tags: Javascript

Posted on Fri, 11 Oct 2019 11:52:38 -0700 by vjbrantner@purd