Question is in the title. I've just tried to run next statements in Chrome console and got strange (as for me) result:
true == 'true' // returns false
'true' == true // returns false
Why does it go such way? Why doesn't typecast work there, but in the next statement works?
if ('true') true // returns true
“Truthy” and “falsy” expressions only evaluate as equal to explicit booleans if you are not using strict comparisons. In this example, the first comparison considers the string “1” equal to true because it uses the non-strict equals operator (==).
The '==' operator tests for abstract equality i.e. it does the necessary type conversions before doing the equality comparison. But the '===' operator tests for strict equality i.e it will not do the type conversion hence if the two values are not of the same type, when compared, it will return false.
Yes. Can we convert the other operand to a string? Yes ( String(true) === "true" // true )
In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy. That is, all values are truthy except false , 0 , -0 , 0n , "" , null , undefined , and NaN .
Because they don't represent equally convertible types/values. The conversion used by ==
is much more complex than a simple toBoolean
conversion used by if ('true')
.
So given this code true == 'true'
, it finds this:
"If
Type(x)
isBoolean
, return the result of the comparisonToNumber(x) == y
."
So you see it starts by becoming ToNumber(true) == 'true'
, which is 1 == 'true'
, and then tries again, where it now finds:
If
Type(x)
isNumber
andType(y)
isString
, return the result of the comparisonx == ToNumber(y)
.
So now it's doing 1 == ToNumber('true')
, which is 1 == NaN
, which of course is false
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With