-3

I have a snippet of javascript that is behaving quite oddly. It's supposed to be filtering items based on an integer.

It works well in 3 of the 4 ranges that it's supposed to filter on, but fails on the largest of them.

The code:

if ((range_low <= itemLeadtime) && (range_high > itemLeadtime)) {
    console.log(range_low +" <= " + itemLeadtime +" && "+ range_high +" > " + itemLeadtime)
    ...
}

And on the range where it behaves oddly, it logs:

120 <= 40 && 9000 > 40

Why?

UrhoKarila
  • 354
  • 5
  • 26
  • do you mean to have `||`? – Daniel A. White Aug 22 '17 at 14:01
  • 2
    try to do: `console.log(typeof range_low, typeof itemLeadtime, typeof range_high)` and give us response. I believe not all are integers but strings. In this case use `parseInt` function to parse from string to integer. – tilz0R Aug 22 '17 at 14:01
  • 1
    @PatrickEvans when it "fails" it prints error, so it enters to if. – tilz0R Aug 22 '17 at 14:02
  • 1
    At least related: [*Why is string “11” less than string “3”?*](http://stackoverflow.com/questions/10863092/why-is-string-11-less-than-string-3) – T.J. Crowder Aug 22 '17 at 14:03
  • `console.log(typeof range_low, typeof itemLeadtime, typeof range_high)` yields `string string string`. That answers that. – UrhoKarila Aug 22 '17 at 14:05

1 Answers1

2

It looks like, you are using strings instead of numbers.

var range_low = '120',
    range_high = '9000',
    itemLeadtime = '40';
    
if ((range_low <= itemLeadtime) && (range_high > itemLeadtime)) {
    console.log(range_low +" <= " + itemLeadtime +" && "+ range_high +" > " + itemLeadtime);
}

With numbers

var range_low = 120,
    range_high = 9000,
    itemLeadtime = 40;
    
if ((range_low <= itemLeadtime) && (range_high > itemLeadtime)) {
    console.log(range_low +" <= " + itemLeadtime +" && "+ range_high +" > " + itemLeadtime);
} else {
    console.log('else');
}
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358