Reputation: 487
Accidently, I found that I can compare an array as if it's a number in javascript.
[3] > 4
false
[3] < 4
true
[3] > [4]
false
[3] < [4]
true
[] > 0
false
[] < 0
false
[] == 0
true
[] === 0
false
[] < 3
true
['3'] == 3
true
['3'] < 3
false
['3'] < 4
true
[3, 4] > [3.5, 2.5]
false
[3, 4] > [2.5, 2.5]
true
Is it okay to use this concept? Then which specification section is it from?
(I tested it in the chrome console.)
Upvotes: 1
Views: 86
Reputation: 1161
Implicit coercion of JavaScript is at work in this case. For example, in the example of a < b
where a and b are of different types, 'Abstract Relational Comparison' algorithm '...first calls ToPrimitive coercion on both values, and if the return result of either call is not a string, then both values are coerced to number values using the ToNumber operation rules, and compared numerically.'
Upvotes: 2