Search code examples
javascriptarraysfunctionundefined

Why am I getting an 'undefined' when I try to call my function?


I am trying to loop through an array that contains multiple arrays in it. The array looks like this. var numsArr = [ [1, 2, 3, 4], [5, 6], [7, 8, 9, 10, 11]];

I already tried doing a basic for loop (I = 0; I < numsArr.length; I++). and when I try to return numsArr[I] I get get back all the arrays but I also get an 'undefined' at the end, after all the array get returned.

This is what I have as my code.

var numsArr = [ [1, 2, 3, 4], [5, 6], [7, 8, 9, 10, 11]];

function looper(){
  for(let i = 0; i < numsArr.length; i++){
    console.log(numsArr[i])
  }
}
console.log(looper())

I expected the outcome to to be each array in the array numsArr, and it does return each array but with an 'undefined' at the end.

[ 1, 2, 3, 4 ]
[ 5, 6 ]
[ 7, 8, 9, 10, 11 ]
undefined

Solution

  • var numsArr = [ [1, 2, 3, 4], [5, 6], [7, 8, 9, 10, 11]];
    
    function looper(){
      for(let i = 0; i < numsArr.length; i++){
        console.log(numsArr[i])
      }
    }
    
    looper()

    You don't need to console.log() looper(), since it already logs the results.

    Just write looper() at the bottom of your JS, and it should work fine.