Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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'
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading