Common Bugs with Functions
These five bite new programmers within their first month of writing functions.
From Bee: "I see this exact bug in beginners every week. Read it once, and you'll spot it on yourself before it bites."
Forgetting return
js
function double(n) {
n * 2; // calculated but discarded
}
console.log(double(5)); // undefined⚠️
Why this happens
Without return, the function runs but gives back nothing.✅
The fix
Add return before the value you want to send back.Returning too early
js
function sum(arr) {
let total = 0;
for (const n of arr) {
return total + n; // returns on first iteration!
}
}
// sum([1,2,3]) is 1, not 6⚠️
Why this happens
The return runs in iteration 1, ending the function before the rest of the array.✅
The fix
Move the return after the loop, not inside it.Mutating arguments by accident
js
function addOne(arr) {
arr.push(1); // mutates the caller's array!
return arr;
}
const xs = [1, 2];
addOne(xs);
// xs is now [1, 2, 1] — surprise!⚠️
Why this happens
Arrays/objects are passed by reference. Pushing inside the function affects the caller.✅
The fix
Return a new array: return [...arr, 1].Default parameter with a shared object
js
function add(item, list = []) {
list.push(item);
return list;
}
add("a"); // ["a"]
add("b"); // ["b"] — fine in JS⚠️
Why this happens
JavaScript is fine here. Python isn't — def f(x, l=[]) shares the same list across calls. Famous Python gotcha.✅
The fix
In Python use def f(x, l=None): l = l or [].Calling a function before it's defined
py
greet("Aisha")
def greet(name):
print(f"Hello, {name}")
# NameError⚠️
Why this happens
Python (unlike JavaScript hoisting) requires functions to be defined before use.✅
The fix
Move definitions to the top of the file, or wrap your top-level call in if __name__ == "__main__": at the bottom.💡
Want the full lesson?
Read Functions — the complete lesson, or test yourself with the quiz.