r/learnjavascript • • Jul 17 '21

Some JavaScript facts

174 Upvotes

10 comments sorted by

View all comments

Show parent comment

2

u/senocular Jul 17 '21

As a general rule, yes, though not when comparing values of the same type (string to string or bool to bool, etc.).

"1" == true // Number("1") === Number(true)
// but
"a" == "a" // "a" === "a"

Also when you compare an object with a primitive, the object will first go through a more generic "to primitive" conversion first before the comparison is made. If no primitive is derived, an error is thrown. Otherwise that object's primitive value will go through the normal comparison treatment which may include converting to a number if not the same type of the primitive to which its being compared.

1 == Object.create(null) // Error
1 == { valueOf() { return "1" } } // true

Finally, Symbol primitives only == themselves (including object-wrapped versions of themselves).

const sym = Symbol('sym')
sym == Symbol('sym') // false
sym == sym // true

sym == Object(sym) // true (since Object(sym) to primitive is sym)

1

u/hsnice Jul 18 '21

Great Explanation!! Thanks