Common Bugs with Functions

📌 Common bugs · functions✍️ Written by Mark Sullivan📅 Reviewed 2026-04-25⏱ ~7 min read

These five bite new programmers within their first month of writing functions.

Bee mascot
From Bee: "I see this exact bug in beginners every week. Read it once, and you'll spot it on yourself before it bites."
#1

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.
#2

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.
#3

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].
#4

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'tdef 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 [].
#5

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.

M
Mark Sullivan
Lead writer · 8 yrs full-stack

Mark started coding in 2017 after switching from financial analysis. She's built production systems in Python (Django) and JavaScript (Node + React) at two startups, and has taught intro programming at his local community college since 2022. He owns the curriculum for variables, functions, conditionals, and loops on this site. More about Mark →