Basic JavaScript - Replace Loops using Recursion

THE TASK Write a recursive function, sum(arr, n), that returns the sum of the first n elements of an array arr.

I dont understand why only 1 of the 5 tests are passing. And why the log is reporting: RangeError: Maximum call stack size exceeded. Ugh I hate recursion…

function sum(arr, n) {
  // Only change code below this line

if (n <= 0) {
  return 0;
}
return sum(arr, n - 1) + arr[n - 1];

  // Only change code above this line
}


console.log(sum([1, 2, 3, 4, 5, 6, 7]), 6);

Your browser information:

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

Challenge: Basic JavaScript - Replace Loops using Recursion

Link to the challenge:

console.log(sum([1, 2, 3, 4, 5, 6, 7]), 6);

Here, you have called sum with only one parameter. That , 6 is in the wrong place.

1 Like

Doh, how embarrassing. But why would the log prevent all those tests from passing? Those tests pass even if I dont use the log.

As you were not passing a required param, js gave that param the value of undefined and that caused an unending series of recursive calls that overflowed the stack (and I guess prevented anything else from running)

1 Like

Javascript does not care how many parameters you pass to a function, regardless of what you put in your declaration. It is up to you to decide what to do if parameters are missing or invalid.

If a parameter is missing, it will be undefined, so you could test for it with if (n === undefined) or if (isNaN(n)) (which should be true as long as n is not a number), then you could throw an error or assign the length of arr to n as a default value.

Here is another way that you could tell Javascript to warn you if a parameter is missing:

const isRequired = () => {
  throw new Error('param is required');
};

function sum(arr, n = isRequired()) {
  // Only change code below this line

  if (n <= 0) {
    return 0;
  }
  return sum(arr, n - 1) + arr[n - 1];

  // Only change code above this line
}


console.log(sum([1, 2, 3, 4, 5, 6, 7])); // missing n
2 Likes

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