I have a function called sum
this function should return the sum of sequential numbers for instance, if I gave the sum
number 5
it should returns 1 + 2 + 3 + 4 + 5 = 15
i did it with forloop
but I'm wondering if it can be done with reduce()
method in Javascript
this is my code
update with @Andrew Morton answer it was done like that.
//const sum = num => {
//let newn = 0;
//for(let i = 0; i <= num; i++) newn += i // 1+2+3+4+5=15
// return newn;
//}
//console.log(sum(5)); // 15
// Andrew solution
const sum = num => {
return (num * (num+1))/2;
}
console.log(sum(5));