Why Doesn't >= (greater Than Or Equals) Comparison Work In Javascript?
Solution 1:
03000
equals 1536
as a decimal.
This is because the leading zero causes the value to be interpreted as an octal.
Since in the end you are doing number value comparisons, why not omit the leading zero in your comparison?
elseif(thiszip>=3000&&thiszip<=3899) {
otherwise, use parseInt
and declare decimal:
elseif (thiszip >= parseInt(03000, 10) && thiszip <= parseInt(03899, 10)) {
// ^^^ pass radix parameter ^^^ pass radix parameter
And you probably want to parseInt
the value being passed in:
var thiszip = parseInt(zip, 10);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_typeshttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
Solution 2:
If a number starts with zero in javascript it can be treated as octal.
Quote from the following docs...
If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
However that's not the only thing at play here. If you were only comparing octals cast as decimals you would get the output you expect. In chrome 43 passing in a number that cannot be converted to octals (any digit has an 8 or 9) will keep it as a base 10.
That is probably why if
statements before Rhode Island gave you the output you expected. For Example you might have passed in a zip of 03274 expecting New Hampshire and you would get what you expect. The if statement is actually doing this...
03274 >= 03000 && 03274 <= 03899
converts to...
1724>=1536&&1724<=3899
However when you pass in 02897 expecting Rhode Island the logic is going to evaluate to True on the New Hampshire if statement. Here's what the actual comparison is...
02897 >= 03000 & 02897 <= 03899
converts to....
2897>=1536&&2897<=3899
See Kevin's answers for how to actually fix the function to work as intended.
Post a Comment for "Why Doesn't >= (greater Than Or Equals) Comparison Work In Javascript?"