Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does true == 'true' statement in JS return false? [duplicate]

Tags:

javascript

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
like image 249
bsiamionau Avatar asked Oct 30 '13 18:10

bsiamionau


People also ask

Why is true == true/false in JavaScript?

“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 (==).

What does true === false mean?

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.

Is true and true same in JavaScript?

Yes. Can we convert the other operand to a string? Yes ( String(true) === "true" // true )

What is true true in JS?

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 .


1 Answers

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) is Boolean, return the result of the comparison ToNumber(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) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).

So now it's doing 1 == ToNumber('true'), which is 1 == NaN, which of course is false.

like image 112
Blue Skies Avatar answered Oct 29 '22 08:10

Blue Skies