Reputation: 4684
I ran into this (unexpected) bug while trying to make a JavaScript function that gets a single post by id, from an array of objects:
let posts = [
{id: 1, title: "Lorem ipsum dolor sit amet"},
{id: 2, title: "Numquam natus culpa non dignissimos dicta"},
{id: 3, title: "Tenetur culpa accusamus"}
];
let singlePost;
function findById(array, id) {
singlePost = array.find(function(post){
console.log(post.id);
return post.id === id;
});
}
singlePost = findById(posts, 2);
console.log(singlePost);
For a reason I have not figured out, console.log(singlePost)
outputs undefined
.
Where is my mistake?
Upvotes: 0
Views: 71
Reputation: 21
You are setting a variable without the function returning anything, so replace the assignment of the variable within the function with a return
let posts = [
{id: 1, title: "Lorem ipsum dolor sit amet"},
{id: 2, title: "Numquam natus culpa non dignissimos dicta"},
{id: 3, title: "Tenetur culpa accusamus"}
];
let singlePost;
function findById(array, id) {
return array.find(function(post){
return post.id === id;
});
}
singlePost = findById(posts, 2);
console.log(singlePost);
Upvotes: 1
Reputation: 4684
Of course, the function was not returning the singlePost
itself. Here is what I should have done:
let posts = [
{id: 1, title: "Lorem ipsum dolor sit amet"},
{id: 2, title: "Numquam natus culpa non dignissimos dicta"},
{id: 3, title: "Tenetur culpa accusamus"}
];
let singlePost;
function findById(array, id) {
singlePost = array.find(function(post) {
return post.id === id;
});
return singlePost;
}
singlePost = findById(posts, 2);
console.log(singlePost);
Upvotes: 0
Reputation: 404
Because your function is returning undefined
and you are assigning it to singlePost
. You can check below.
findById(posts, 2);
console.log(singlePost); // This will console.log the value of singlePost
Upvotes: 1