Find the bug · #36 · Loops and closures Hard JavaScript
Every email is “not found”
The forgot-password page looks users up by email and never finds anyone.
On this page
The report
The “forgot password” page looks the user up by email. It says “No account with that email” for every address, including ones that definitely exist.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Finds a user by email, or returns null.
function findUser(users, email) {
users.forEach((u) => {
if (u.email === email) return u;
});
return null;
}Read it, then pick a line.
Line 4 says return u. Return from which function?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
const users = [{ name: 'Asha', email: 'asha@x.in' }, { name: 'Ravi', email: 'ravi@x.in' }];
console.log(findUser(users, 'ravi@x.in')?.name ?? 'not found');It prints
not found
It should print
Ravi
Show the answer: the bug, the fix, and how you’d find it
The bug (lines 3, 4)
Line 4’s return u is inside the arrow function passed to forEach, so it only returns from that callback, for that one user. forEach ignores what callbacks return and can’t be stopped early, so findUser always carries on to return null. Use find, which stops at the first match and returns it.
The fix
1// Finds a user by email, or returns null.2function findUser(users, email) {3 users.forEach((u) => {4 if (u.email === email) return u;5 });6 return null;3 return users.find((u) => u.email === email) ?? null;7}How you’d find it
- Reproduce with an email that’s definitely in the list:
null. - Put a log next to
return u: it runs. So the match is found, and the value is being lost. - Look at which function that
returnbelongs to: the callback.forEachthrows the value away, and the outer function returns null.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
const users = [{ email: 'a@x.in' }, { email: 'b@x.in' }];
assert.equal(findUser(users, 'b@x.in'), users[1]);
assert.equal(findUser(users, 'z@x.in'), null);Where else this bites
- You can’t
breakout offorEacheither; usefor...ofwhen you need to stop early. - A
returninsidemaporfiltercallbacks means something different again.