Search code examples
typescriptforeachreturn-value

return value from .forEach() indise a function in TypeScript


I'm trying to make a return from a .forEach() inside a function, but it always return 'There is no book with this name' even when the condition is true.

code:

function getBookByName(books:[], name: string): object | string {
   books.forEach((book) => {
        if (book.name === name) {
            return book
        }
    })
    return 'There is no book with this name'
}

Solution

  • The forEach function takes another function (callback) as a parameter and ignores it's returned value, therefore your return never stops the execution.

    forEach() executes the callbackFn function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

    Note: There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

    For this case it's better to use array.find()

    const books = [ { name: "test" }];
    
    function getBookByName(books, name){
      return books.find((book) => book.name === name) || 'There is no book with this name';
    };
    
    console.log(getBookByName(books, "test"));
    console.log(getBookByName(books, "test2"));

    TypeScript Playground