skip to Main Content
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


  1. Give return statement outside of loop.

    let amd = 'c';
    const arr = ['a', 'b', 'c'];
    
    function getSum(acc, arr) {
     for (let i = 0; i < arr.length; i++) {
      acc = acc + arr[i];
     }
     return acc;
    }
    
    console.log(getSum(amd, arr));
    
    Login or Signup to reply.
  2. The reason is it will return after first iteration of for loop. Change it to

    let amd = `c`;
    const arr = ['a', 'b', 'c'];
    
    function getsum(acc, arr){
        for( i = 0; i< arr.length; i++){
          acc = acc + arr[i];
        }
        return acc
    }
    console.log(getsum(amd, arr));
    
    Login or Signup to reply.
  3. 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.

    let amd = `c`;
    const arr = ['a', 'b', 'c'];
    
    
    function getsum(acc, arr){
        for( i = 0; i< arr.length; i++){
            acc = acc + arr[i];
        }
        return acc;
    }
    console.log(getsum(amd, arr))
    

    happy coding!

    Login or Signup to reply.
  4. Because function return in first loop iterration.
    correct form of this code is given bellow

    let amd = `c`;
    const arr = ['a', 'b', 'c'];
    
    
    function getsum(acc, arr){
        
        for( i = 0; i< arr.length; i++){
           acc = acc + arr[i];
        }
        return acc;
    }
    
    Login or Signup to reply.
  5. Full Code :-

    let amd = `c`;
    const arr = ['a', 'b', 'c'];
    
    
    function getsum(acc, arr){
        for( i = 0; i< arr.length; i++){ 
          
          var acc = acc + arr[i];
        }
         
        return acc;
    }
    console.log(getsum(amd, arr));
    

    Explanation :-

    1. 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)

    2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search