Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"Infinity" if I don't pass any number as parameters

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

// 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]));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading