JavaScript number comparison giving wrong results

I am attempting to create a 3 field search, hiding and showing cards depending on if they meet the criteria. query1, and query2 work just fine, but for some reason, query3 doesn’t work as intended. I used a console log to figure out what is happening and the result are baffling.

const marketSearchFunction = function() {
  const query1 = $('#market-search').val().toLowerCase();
  const query2 = parseFloat($('#market-min').val());
  const query3 = parseFloat($('#market-max').val());
  let boolean1 = false
  let boolean2 = isNaN(query2) ? true : false
  let boolean3 = isNaN(query3) ? true : false
    const price = parseFloat($(this).find('.price').data('value'))
    boolean1 = $(this).text().toLowerCase().indexOf(query1) !== -1
    boolean2 = (boolean2 ? boolean2 : (price >= query2))
    boolean3 = (boolean3 ? boolean3 : (price <= query3))
    console.log(price, query3, boolean3, (price <= query3))
    showCard($(this), (boolean1 === boolean2 === boolean3))

Here is the console log output

  • NaN 1500 false false
  • (2) 1500 1500 true true
  • 2000 1500 true false
  • 1800 1500 true false

Why does the system set boolean3 to true, when the value of the comparison is false?

1800 is NOT less than 1500, yet it sets it to TRUE. I restarted the server, I moved the code about. I’m not sure what I’m doing wrong.


Not a direct answer to your question but hopefully a fix for your problem.

Regardless of the logic errors in your current code, I think you can simplify your logic and therefore make it less error prone and easier to reason about. I believe the core issue is that you are sharing the boolean* variables across all iterations.

Also use meaningful variable names:

const marketSearchFunction = function() {
  const query = $('#market-search').val().toLowerCase();
  let minPrice = parseFloat($('#market-min').val());
  let maxPrice = parseFloat($('#market-max').val());

  // Using -Infinity and Infinity lets us keep the price comparison
  // logic simple
  if (isNaN(minPrice)) minPrice = -Infinity;
  if (isNaN(maxPrice)) maxPrice = Infinity;

    const price = parseFloat($(this).find('.price').data('value'));
    const shouldShow =
      $(this).text().toLowerCase().indexOf(query1) !== -1
      && price >= minPrice
      && price <= maxPrice;

    showCard($(this), shouldShow);