0

In ES5, The Abstract Equality Comparison Algorithm:

If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.

To Number Conversions Algorithm:If x is an Object, the firstStep is to get primValue, and then it will return ToNumber(primValue).

To Primitive Conversions Algorithm: Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object, passing the optional hint PreferredType.

[[DefaultValue]] uses "valueOf" method, and returns a primitive value.

The question is: Object.ValueOf method gets a Object value not a primitive Value. it confuses me .

let a=[]
let b=a.valueOf()// object a
console.log(b)
let c=a.toString()//undefined
console.log(c)
typeof b //object
typeof c //string
  • 2
    Does this answer your question? [Why do both "\[\] == true" and "!\[\] == true" evaluate to false?](https://stackoverflow.com/questions/58255112/why-do-both-true-and-true-evaluate-to-false) [2](https://stackoverflow.com/questions/27523765/how-does-js-type-coercion-work) – shrys Feb 01 '23 at 06:12
  • JavaScript has always done strange type conversions when comparing values and on addition. Use `===` to compare values. It returns `false` if the two values have different types and avoids promiscuous type conversions. – axiac Feb 01 '23 at 06:14
  • ES5 is quite outdated; we’re at ECMAScript 2022 (13th edition), currently, though you can also refer to the living spec, currently referring ECMAScript 2023. [ToPrimitive](//tc39.es/ecma262/#sec-toprimitive) coercion forces a primitive via [OrdinaryToPrimitive](//tc39.es/ecma262/#sec-ordinarytoprimitive). Since `valueOf` doesn’t return a primitive, `toString` is used instead. _`a.toString()`_ is not `undefined`; The _statement_ `let c = a.toString();` results in a completion record with the value `undefined`. Now you have the same scenario as `"" == 0`, and can recursively continue from there. – Sebastian Simon Feb 01 '23 at 06:20
  • The default implementation of the `valueOf` method returns the object itself, array in this case. So JS ends up calling `toString` method to convert the object into a primitive value. Empty array when converted to a primitive value is coerced into an empty string. So the comparison becomes `"" == 0`. This comparison is ultimately coerced to `0 == 0` which is true. – Yousaf Feb 01 '23 at 06:23

0 Answers0