This function has to add all the constants in the array recursively using JavaScript. Any idea why I'm getting a type error in this recursion function?
const slowAdd = (array) => {
if (array.length === 0) return 0;
const restOfArray = array.slice(1);
return array[0] + slowAdd(array[restOfArray]);
}
const dataArray = [2, 5, 7]
slowAdd(dataArray);
Same Problem with using helper function:
const fastSum = (array) => {
return _fastSum(array, 0);
};
const _fastSum = (array, start) => {
if (start === array.length) return 0;
return array[start] + _fastSum(array, start + 1);
}
const dataArray = [2, 5, 7]
console.log(fastSum(dataArray));
Why does the fastSum recursion work, but the first doesn't.
array[restOfArray]is a single number, not a different array. EDIT: OK, actuallyrestOfArrayis the rest of the array. I misread it and thought it was just an index. At any ratearray[restOfArray]certainly doesn't produce another array andslowAdddoes expect an arrayundefinedrestOfArraywould be an index. However, when it's an array, then most of the time it's going to produceundefinedas you said.