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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! That point 4(a) string comparison prefix criteria is pretty interesting too.
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: "5" is more than "3". This is a purely character-based comparison.
The spec link seems to have some new content now (art therapy for drug addictions).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.