Function Mistakes
And how to avoid them.
Everyone makes the same few mistakes when they start writing functions. Knowing them in advance will save you hours of confusion.

- Everyone makes them
- The same few mistakes
- Know them in advance
Three classic bugs
The first function forgets return, so it gives back undefined. The second prints the answer instead of returning it, so we can't use the result. The third returns it properly. Run it. Only the third gives us a value we can use.
function addA(a, b) { a + b; }
function addB(a, b) { console.log(a + b); }
const addC = (a, b) => a + b;
console.log("forgot return:", addA(2, 3));
const r = addB(2, 3);
console.log("printed, not returned:", r);
console.log("correct:", addC(2, 3));forgot return: undefined 5 printed, not returned: undefined correct: 5
A checklist
When a function gives undefined, check for a missing return. When you can't use a result, check you returned it, not printed it. When something runs too early, look for brackets on a callback. And when a function changes something unexpectedly, look for side effects.
| key | value |
|---|---|
| undefined? | missing return |
| Can't use result? | printed, not returned |
| Ran too early? | fn() instead of fn |
| Strange changes? | side effects |
Calling before it exists
Another classic mistake. Function declarations can be called before they appear in the file, because they're hoisted. But arrow functions stored in const can't. Calling one too early throws a reference error. Here we catch the error, so we can see its name. Run it.
console.log(declared(2));
try {
console.log(arrow(2));
} catch (e) {
console.log(e.name);
}
function declared(n) { return n * 10; }
const arrow = (n) => n * 10;20 ReferenceError
Summary
Watch for missing returns, printing instead of returning, and calling callbacks too early. Next, a quiz on functions.
Key takeaways- Return your result
- Don't just print
- Pass fn, not fn()