Skip to content

Instantly share code, notes, and snippets.

@LearningMaterial
Forked from amysimmons/coercion-gotchas.md
Created February 27, 2018 13:33
Show Gist options
  • Save LearningMaterial/d281abfb7c7e00e62ee5ee58e0c3c27a to your computer and use it in GitHub Desktop.
Save LearningMaterial/d281abfb7c7e00e62ee5ee58e0c3c27a to your computer and use it in GitHub Desktop.
false == "0" // true
// false gets coerced to 0
// "0" gets coerced to 0
// 0 == 0 is true 

false == 0 // true
// false gets coerced to 0
// 0 == 0 is true

false == "" // true
// false gets coerced to 0
// "" gets coerced to a number, 0
// 0 == 0 is true

false == [] // true
// false gets coerced to 0
// [] is an object so ToPrimitive would be called on it
// valueOf() would be consulted to find a primitive
// [].valueOf() would result in [], not a primitive value
// so [].toString() would be called, resulting in ""
// "" would then get coerced to a number, 0
// 0 == 0 is true

"" == 0 // true
// "" gets coerced to a number, 0
// 0 == 0 is true

"" == [] // true
// [] is an object so ToPrimitive would be called on it
// valueOf() would be consulted to find a primitive
// [].valueOf() would result in [], not a primitive value
// so [].toString() would be called, resulting in ""
// "" == "" is true

0 == [] // true
// [] is an object so ToPrimitive would be called on it
// valueOf() would be consulted to find a primitive
// [].valueOf() would result in [], not a primitive value
// so [].toString() would be called, resulting in ""
// "" would then get coerced to a number, 0
// 0 == 0 is true

Sources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment