Return Largest Numbers in Arrays(question)

Explain, please, how exactly this condition works !arr.length ?

I understand that while it is false, the maximum element of each subarray will be added to the new one. But what is the logic behind this condition?
I understand this as: “if it is impossible to calculate the length of the array, then …”
But how it can be…

function largestOfFour(arr, finalArr = []) {
  return !arr.length
    ? finalArr
    : largestOfFour(arr.slice(1), finalArr.concat(Math.max(...arr[0])))

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

Challenge: Return Largest Numbers in Arrays
Link to the challenge:

It’s not quite saying it is “impossible to calculate the length of the array.” It is saying “if the length of the array is 0.” Remember, 0 is a falsey value in JS.

You are either returning finalArr or you are making a recursive call. Every time you make the recursive call you are passing arr.slice(1) as the first argument. The key is understanding what that does. Once you understand that you will see that you will eventually get to the base case (!arr.length).

If you don’t understand it then try typing some examples into your browser’s dev tools console. What gets returned when you try [4,3,2,1].slice(1)? Then apply slice(1) to that return value. And so on.

1 Like

I think I got it. So here !arr.length, implied as if arr.length = 0 ?
Because at the beginning the length is 9(for example), but after the last return of the recursion it will become 0 and return the finalArr

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.