Why is the value "" <{} true?

In JavaScript, why:

"" < {}rate trueand

"" < []rate it false?

+4
source share
1 answer

Because it <forces its arguments. He prefers to compare numbers, but if the objects do not support a numerical primitive value, he executes the lines, and you end up doing lexical comparison. String({})- "[object Object]"but String([])- "". "" < "[object Object]" truebut "" < ""- false.

All gora details in the specification (fair warning, language mildly expressed).


:

, , Number({}) NaN, Number([]) - 0. NaN < 0 false, 0 < NaN. ?

, , , "... ..." ( ). . . , ( ), :

  • < abtract ToPrimitive .
  • , [[DefaultValue]] "" "".
  • [[DefaultValue]] (hint = Number) valueOf , , ; , [[DefaultValue]] toString. valueOf ( ) , [[DefaultValue]] toString.
  • < , .

, ToPrimitive , < ; Number (, JavaScript , , ), Number#valueOf [[DefaultValue]], Number#valueOf . < .

, ??

+6

Source: https://habr.com/ru/post/1535328/


All Articles