Home > Software engineering >  "Infinity" if I don't pass any number as parameters
"Infinity" if I don't pass any number as parameters

Time:10-08

Having this issue most likely I am doing everything wrong, but I wanted to find the smallest and the biggest number inside an array and return it to a new object, and if this array is empty I wanted to have a simple empty object. This is the logic I have used

    function findBiggestAndSmallest(numbers) {
      const biggest = Math.max(...numbers);
      const smallest = Math.min(...numbers);
      if (numbers === []) {
        return {};
      }
      return { biggest, smallest };
    }
    
    console.log(findBiggestAndSmallest([]));
    console.log(findBiggestAndSmallest([2,1,5,100,20]));

and it's working fine as long I put numbers inside the array but when I leave an empty array the result is -infinity and Infinity, even though I specified that if the parameter is an empty array just return an empty object.

Thank you for your support.

CodePudding user response:

The if statement "if(numbers === [])" is a comparison of arrays, which are a special type of objects. Objects are stored with their references so you cannot compare the content equality of arrays in this manner because the comparison will check if the two objects are pointing towards the exact same place in memory.

// This never works
console.log([]===[])


function findBiggestAndSmallest(numbers) {
  // Always do error handling first :)
   if (!numbers.length) {
    return {};
  }

  const biggest = Math.max(...numbers);
  const smallest = Math.min(...numbers);

  return { biggest, smallest };
}

console.log(findBiggestAndSmallest([]));
console.log(findBiggestAndSmallest([2,1,5,100,20]));

  • Related