Search code examples
javascriptasynchronousreturnanonymous-function

Returning from an anonymous function won't work, even though it's not async


I have the following function:

function filterDesiredURLs(tweet) {
    tweet.entities.urls.forEach((url) => {
        desiredURLs.forEach((regexPattern) => {
            if (regexPattern.test(url['expanded_url'])) {
                console.log('hello, im returning');
                return true;
            }
        })
    })
}

And I'm calling it like this:

console.log(filterDesiredURLs(tweet));

Where tweet is a defined object. I can see that the function is indeed returning because I see the output hello, im returning in the console, but the console.log(filterDesiredURLs(tweet));prints undefined. I would expect this for anonymous functions passed as callbacks for async operations, but this is not async, so the return should work. What's happening?


Solution

  • return doesn't operate across function boundaries. It only returns from the innermost function. To do what you want you probably want filter or find coupled with some:

    function filterDesiredURLs(tweet) {
      // First, you were missing a return in the outer function
      // Without a return here, *this* function will return `undefined`
      return tweet.entities.urls.filter(url => {
        // We are using `filter` to reduce the URL list to only
        // URLs that pass our test - this inner function needs to return
        // a boolean (true to include the URL, false to exclude it)
        return desiredURLs.some(regexPattern => {
          // Finally, we use `some` to see if any of the regex patterns match
          // This method returns a boolean value. If the function passed to it ever 
          // returns true, it terminates the loop and returns true
          // Otherwise, it iterates over the entire array and returns false.
          return regexPattern.test(url['expanded_url']);
        });
      });
    }