Imagine you have an array like this:
const novels = [
{
id: 1,
name: 'The Da Vinci Code',
genre: 'Mystery',
author: {
name: 'Dan Brown',
birthYear: 1964,
},
releaseYear: 2003,
},
{
id: 2,
name: 'To Kill a Mockingbird',
genre: 'Drama',
author: {
name: 'Harper Lee',
birthYear: 1926,
},
releaseYear: 1960,
},
{
];
If we want to find and display the book with the longest title, we can use the following code snippet:
const findLongestTitle = () => {
const longestTitle = novels.reduce((prevBook, currentBook) => {
if (currentBook.name.length > prevBook.name.length) {
return currentBook;
}
return prevBook;
});
return longestTitle
}
console.log(findLongestTitle().name);
The question at hand is why it's necessary to access .name property while calling the function instead of directly returning book.name / accumulator.name inside the function. If attempted without accessing .name, the result turns out to be undefined.
const findLongestTitle = () => {
const longestTitle = novels.reduce((prevBook, currentBook) => {
if (currentBook.name.length > prevBook.name.length) {
return currentBook.name;
}
return prevBook.name;
});
return longestTitle
}
console.log(findLongestTitle());