Summing numbers between one and a given number without recursion is simple:
function sumNums (num) {
let array = [];
for (let i = 0; i <= num; i++) {
array.push(i);
}
return array.reduce((a, b) => a + b);
}
console.log(sumNums(3));
6
But what I don't understand, is that when we're using recursion, it causes the "loop" to occur throughout the entire function.
So if we have a for-loop (or any loop) within a function that's using recursion, it will cause an error - right?
And I assume that we'll need an array of the integers in order to reduce them - So know how else can we create an array of integers between one and and a given number without using some sort of loop?
EDIT: A simpler way of adding integers between 1 and num without recursion:
function sumNums (num) {
let sum = 0;
for (let i = 1; i <= num; i++) {
sum += i;
}
return sum;
}
console.log(sumNums(3));
No need to add the integers to an array and then reduce it. Just add them to an initializer variable instead.