Any way to signify infinity / negative infinity?

Tell us what’s happening:

Your code so far


function largestOfFour(arr) {
let finalArr = []
for (let i=0; i < arr.length; i++){
  let holder = -9999999
  for (let j=0; j < arr[i].length; j++){
    let checkArr = arr[i][j]
    if (checkArr > holder){holder = checkArr}
  }
finalArr.push(holder)
}
return finalArr;
}

console.log(largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36.

Challenge: Return Largest Numbers in Arrays

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays

I was doing this challenge and initially I had “let holder = 0” as though all numbers passed through the function would be positive. Obviously this didnt work as the last check has an array with all negative numbers so i changed it to an arbitrary very low number as can be seen. While this worked to get me past this challenge, I was wondering if there is a better method for me define the holder variable such that it will work with all negative numbers no matter how ridiculously long, or if thats simply a flaw of solving this problem using nested for loops.

You can use the first number in the array.

Yes but i mean such that any array can be put in without knowing what it will be beforehand

There is a constant, but as Jeremy said, you don’t need it. You don’t need to know anything about the array ahead of time.

1 Like

Yes. You use the first number in the array.

  let holder = arr[i][0];
  for (let j = 1; j < arr[i].length; j++){
    let checkArr = arr[i][j]
    if (checkArr > holder) {
      holder = checkArr
    }
  }

Using negative infinity isn’t really needed. You should always think of ways to do less work in a function. In this case, we removed one loop iteration.

1 Like

If the largest number is not the first number, then the j loop updates the value of holder when it finds a larger number. Nothing falls apart.

1 Like

Yayaya u right, thank u for ur time you’ve helped my understanding greatly :smiley:

1 Like