r/learnjavascript • • Jul 17 '21

Some JavaScript facts

174 Upvotes

10 comments sorted by

View all comments

11

u/senocular Jul 17 '21

"When we compare two values using "==", And both values are of different types, then javascript tries to convert the type of one value.

This is not entirely true. In some cases both values are converted, for example with string-boolean comparisons. In that case both are converted to numbers.

"2" == true // false
"true" == true // false
// because
Number("2") == Number(true) // false
Number("true") == Number(true) // false
// and not
Boolean("2") == true // true
"true" == String(true) // true

There's also an exception with undefined/null comparisons:

document.all == undefined // true
document.all == null // true

3

u/hsnice Jul 17 '21

Oh! okay, thanks.

And what I think is that when we compare using '==', it always converts both values in number.

"true" == true   // false  

Number("true")  // NaN  

"0" == false  // true
  
Number("0")   // 0
  
Number(false)  // 0  

"1" == true  // true

Number("1")  // 1 
 
Number(true)  // 1

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