JS Logical Madness

This code returns min

how is this possible?

if(prices[i] == 1000 && min == 53){
  if(prices[i] < min){
    return min;
  }
  return prices[i];
}

      

+3


source to share


2 answers


Values ​​are strings. When you use them ==

to compare them with numbers, the numbers are first (internally) converted to strings. However, it <

compares the two strings as strings, and therefore the string "1000" is actually smaller than the string "53" because "1" precedes "5" in the character set.



+5


source


Funny things happen when you compare strings, not numbers



console.log("strings", "1000" < "53")
console.log("numbers", 1000 < 53)
      

Run codeHide result


+3


source







All Articles