C. id is not converted to number before comparison
D. res.send called twice without return
Solution
Step 1: Check flow after 404 response
If product not found, res.status(404).send is called but code continues without return.
Step 2: Identify multiple responses sent
After 404 response, code still filters products and calls res.send again, causing error.
Final Answer:
res.send called twice without return -> Option D
Quick Check:
Multiple res.send calls without return cause errors [OK]
Hint: Use return after sending response to avoid multiple sends [OK]
Common Mistakes:
Not returning after sending 404 response
Ignoring type conversion for id
Assuming route path is wrong
5. You want to create a DELETE route that removes a book by its ID from a nested data structure where books are grouped by genre. Which approach correctly handles deletion and sends a 404 if the book is not found?
const library = {
fiction: [{id: 1, title: 'A'}, {id: 2, title: 'B'}],
nonFiction: [{id: 3, title: 'C'}]
};
app.delete('/books/:id', (req, res) => {
const id = Number(req.params.id);
let found = false;
for (const genre in library) {
const index = library[genre].findIndex(book => book.id === id);
if (index !== -1) {
library[genre].splice(index, 1);
found = true;
break;
}
}
if (found) {
res.status(200).send('Book deleted');
} else {
res.status(404).send('Book not found');
}
});
hard
A. The code does not break after deletion, causing multiple deletions
B. This code correctly deletes the book and handles 404 if not found
C. The code misses converting id to number, causing no matches
D. The code sends 200 status even if book is not found
Solution
Step 1: Check id conversion
id is converted to Number, ensuring correct comparison with book ids.
Step 2: Verify loop and deletion logic
Loop checks each genre, finds book by id, deletes it, sets found true, and breaks loop to avoid extra deletions.
Step 3: Confirm response handling
If found is true, sends 200 with 'Book deleted'; else sends 404 with 'Book not found'.
Final Answer:
This code correctly deletes the book and handles 404 if not found -> Option B
Quick Check:
Proper id conversion, deletion, and response = correct code [OK]
Hint: Convert id, break loop after deletion, send 404 if not found [OK]
Common Mistakes:
Not converting id to number before comparison
Not breaking loop after deletion
Sending success response even if book missing
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.