let amd = 'c';
const arr = ['a', 'b', 'c'];
function getsum(acc, arr) {
for (i = 0; i < arr.length; i++) {
return acc = acc + arr[i];
}
}
console.log(getsum(amd, arr));
Could someone please explain why it gives me just ca
?
I was expecting cabc
5
Answers
Give return statement outside of loop.
The reason is it will return after first iteration of for loop. Change it to
Since return exists inside the for loop, the for loop is terminated when it encounters return .
Modifying the code like this will give you the desired result.
happy coding!
Because function return in first loop iterration.
correct form of this code is given bellow
Full Code :-
Explanation :-
In first loop value of acc will be (ca) and then when i = 1 value of acc will be (cab) and then again when i = 2 value of acc will be (cabc) and then again when i = 3 condition will get false and then it will return whole output which is (cabc)
Have returning output outside the for loop because first it will get the complete from the for loop then it will return whole output which it stored in acc variable