AI Hints
Home›JavaScript Tutorial›Better Functions
JavaScript · Lesson 41 of 138

Function Mistakes

And how to avoid them.

⏱ 2 min read▶ Video at 49:10🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Everyone makes the same few mistakes when they start writing functions. Knowing them in advance will save you hours of confusion.

Function Mistakes
From the video: Function Mistakes
  • 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.

app.jsjavascript
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));
Output
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.

keyvalue
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.

app.jsjavascript
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;
Output
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()
Next up: Functions Quiz — test yourself