JavaScript enforcement type

I assume that I know the differences between == and === in JavaScript, this is what == will do type coercion when comparing, but === will not. I understand that the following code will be true:

console.log(true == "1"); 

but when is the code below false?

 console.log(true == "true"); 
+5
source share
2 answers

If you freely compare a boolean value with a value of another type, the boolean value is forcibly entered into a number.

And when you compare the number and the string, the string is forcibly entered into the number.

Complete rules are explained in the Abstract Equality Comparison Algorithm

The process is as follows:

 true == "true" ─┐ β”œβ”€ Number(true) // 1 1 == "true" ── β”œβ”€ Number("true") // NaN 1 == NaN ── β”œβ”€ // Comparing with `NaN` always produces `false` false β”€β”˜ 
+4
source

The logical operand is converted to a numerical value, and the strings are converted to a numerical value, since one operand is a number.

The result is 1 == NaN. If either operand is NaN, the equal operator always returns false.

+1
source

Source: https://habr.com/ru/post/1234620/


All Articles