# Can you give a Variable a value of All Numbers

Is there a better way to do this?
In a Javascript lesson I was supposed to return the largest number from each sub-array. My code passed all the tests except for the one involving a sub-array with all negative numbers. I realized this was because the variable I made had an initial value of 0 (var num = 0). Obviously 0 is larger than any negative number so this didn’t pass.
I ended up changing the value to a very large negative number to insure it would return the correct output in most cases. However, I am wondering if there is a way to assign the variable a value of all numbers so this code could provide the proper output given any numbers without being limited by my large negative value?
Here is my code below:

``````function largestOfFour(arr) {
var numArr = [];
for(let a = 0; a < arr.length; a++) {
var num = -1000000000000;
for(let b = 0; b < arr[a].length; b++) {
if(num < arr[a][b]) {
num = arr[a][b];
}
}
numArr.push(num);
}
return numArr;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
``````

In JS there is a number `Infinity`. It can also be negative.

Many folks are using stuff like below for this kind of problems:

``````const arr = [-11212, -55, -33];

console.log(Math.max(...arr));//-33
``````

Thank you Kevin, you’re awesome. Negative infinity works!

``````var num = -Infinity
``````

What if you set the num initially to the first number you see in the array, then if the next number is larger, reset it to that etc?

1 Like