I am having trouble with a small function I have written in that I cannot get the value to return properly. I am wondering if there is a better way to do this than using a .forEach loop.
var userSelectedBook = { id: 1234 };
var bookList = [
{
id: 5678,
color: "blue"
},
{
id: 1234,
color: "red"
}
];
function getBookColor(bookList, userSelectedBook) {
const color = bookList.forEach(book => {
if (book.id === userSelectedBook.id) {
return book.color;
}
});
return color;
}
In the above case, when I call getBookColor() I would expect to receive the response "red" because I am passing the userSelectedBook where the ID is 1234.
However I only get undefined even though putting a console log within the if statement does show the correct color.