Function returns array as as undefined but console.log returns the array with no problem

Hi!

I’m working on a function for a problem set that’s supposed to take both an array of integers and a target number, and return the indices of the two numbers that add up to the specific target as an array.

But for some reason it keeps returning undefined. When I replace “return” with “console.log” , however, it works. I have no idea what I’m missing here. Any help would be appreciated!

Here’s the code below:

function sumFoo(nums, target) {
    nums.forEach((num, index, array) => 
    {
        for (let nextIndex = index + 1; nextIndex < array.length; nextIndex++)  {
           if (num + array[nextIndex] == target) {
               
             var finalArray = [index, nextIndex];
             return finalArray;
           
           }
            
               
        }})};

Try this : declare the finalArray variable just above the For loop.

2 Likes

Thanks! That did the trick, along with returning finalArray outside the .forEach method call.