JavaScript provides two ways to compare values, strictly comparing (===,! ==) and casting (==,! =), strict comparison requires the same type of variables, while non-strict comparison will perform type conversion according to the value of the variable, which is commonly known as implicit type conversion.

What is = =

== is a comparison operator that is converted to the same type before the comparison.

So, when comparing a number to a string, JS converts the string to a number first, an empty string to 0, and a string without a number to NaN, and then compares it.

What is = = =

=== is the strict comparison operator in JS, which returns false for unequal types. When the types are equal, the values are compared for equality.

Why use ==

In a programming language, one comparison operator is sufficient, why two in JS? This is where JS is both flexible and frustrating. We can use == to compare two variables of different types, because it will help us do type conversion and then compare. But it’s also what most people joke about, because its conversion rules are sometimes hard to follow and make it harder to learn.

There are also many companies that have adopted ESLint rules that prohibit the use of == for variable comparisons in their projects, as people who don’t understand the == operator can easily write bugs. Force the === comparison to manually convert the type. This way you know exactly what you’re doing when someone else is maintaining your code.

== 对比 ===

Here are some amazing examples. Did you get them all right?

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

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

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

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

false= ='false' // false
false= ='0' // true
false= =undefined // false
false= =null // false[] [] = =//false[] [] = = =//false because addresses are stored differently in memory= = {} {}//false= = = {} {}//false, similarly, because the address is stored differently in memory

NaN= =NaN //false, NaN is not equal to any value, including NaN
NaN= = =NaN //false, NaN is not equal to any value, including NaN
Copy the code

conclusion

Given the headache-inducing == comparison above, I suggest you never use ==. Instead, always use === = and! = =.

If there are more interesting examples, let me know in the comments section and I’ll fill them in.

If this article is useful to you, your likes, comments and concerns are the biggest encouragement for me O(∩_∩)O👍👍👍