denysdovhan / wtfjs

🤪 A list of funny and tricky JavaScript examples
http://bit.ly/wtfjavascript
Do What The F*ck You Want To Public License
34.95k stars 2.55k forks source link

Non-strict comparison of a number to true (1 == true) #135

Closed markogresak closed 3 years ago

markogresak commented 4 years ago

I was goofing around with JS weirdness today, and I found this behaviour, which took me some time to explain to myself. Maybe it could be included in the file?

It started off with the basic type coercion, which worked as expected:

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

My initial assumption was that the value is cast to Boolean. For this simple example, that assumption would hold

Boolean(1)
// true
Boolean(0)
// false

But it broke when trying the following:

1.1 == true
// false

Given my original assumption, I was a bit confused because I know Boolean(1.1) -> true.

But the true explanation to the first snippet is:

Number(true)
// 1
Number(false)
// 0

Meaning that true/false is cast to and compared as Number.

libook commented 4 years ago
Boolean(1.1)
// true

Hum... interesting.

denysdovhan commented 4 years ago

@markogresak could you open a PR?

denysdovhan commented 3 years ago

Added with an explanation. Will be published soon.

github-actions[bot] commented 3 years ago

:tada: This issue has been resolved in version 1.17.0 :tada:

The release is available on:

Your semantic-release bot :package::rocket: