Wick
Wick

Reputation: 1232

how exactly do Javascript numeric comparison operators handle strings?

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.

Upvotes: 3

Views: 834

Answers (1)

SLaks
SLaks

Reputation: 887305

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.

Upvotes: 4

Related Questions