Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Logical Insanity

This code returns min, how is this possible?

if(prices[i] == 1000 && min == 53){
  if(prices[i] < min){
    return min;
  }
  return prices[i];
}
like image 675
Jonathan Woollett-light Avatar asked Apr 17 '26 19:04

Jonathan Woollett-light


2 Answers

The values are strings. When you use == to compare them to numbers, the numbers are first (internally) converted to strings. However, the < compares the two strings as strings, and as such the string "1000" is in fact less than the string "53", because "1" comes before "5" in the character set.

like image 192
Pointy Avatar answered Apr 19 '26 09:04

Pointy


Funny things happen when you compare strings and not numbers

console.log("strings", "1000" < "53")
console.log("numbers", 1000 < 53)
like image 30
epascarello Avatar answered Apr 19 '26 09:04

epascarello



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!