3
var i = ['5000','35000'];
alert((i[0] < i[1])?'well duh!':'fuzzy math?');
alert((Number(i[0]) < Number(i[1]))?'well duh!':'fuzzy math?');

What's happening here? In the first alert, the text string "5000" evaluates as not less than "35000". I assumed Javascript used Number() when numerically comparing strings, but apparently that's not the case. Just curious how exactly Javascript handles numerically comparing the strings of numbers by default.

Wick
  • 1,222
  • 2
  • 15
  • 21

1 Answers1

4

Javascript compares strings by character value, whether the strings look like numbers or not.

You can see this in the spec, section 11.8.5, point 4.

'a' < 'b' and 'ab' < 'ac are both true.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Thanks! That point 4(a) string comparison prefix criteria is pretty interesting too. – Wick Nov 18 '11 at 03:24
  • Okay I'm still missing something -- I understand your examples above, but I don't understand how the character value of "5000" is not less than the character value of "35000". Can you run me through how the character values are calculated for my specific example? – Wick Nov 18 '11 at 03:39
  • 1
    @Wick: `"5"` is more than `"3"`. This is a purely character-based comparison. – SLaks Nov 18 '11 at 03:56
  • The spec link seems to have some new content now (art therapy for drug addictions). – Teemu Apr 25 '20 at 15:21