Skip to content

/errors/javascript/x-is-not-a-function

TypeError: x is not a function (JavaScript)

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · v24.20.0updated
tool
JavaScript
exit code
1
versions
ECMAScript (all), Node.js and browsers
os
any

TypeError: x is not a function means the code calls something with () that is not a function. The text before "is not a function" is the expression that was called, so user.getName is not a function says that user.getName is undefined (or a non-function value). Check what the value really is with console.log(typeof user.getName), then fix the name, the import or the type.

Reproduce it

bash
cat > app.js <<'EOF'
const user = { name: "Ada" };
console.log(user.getName());
EOF
node app.js 2>&1 | grep TypeError
exit ${PIPESTATUS[0]}

Output · exit 1

TypeError: user.getName is not a function

The usual suspects

bash
cat > cases.js <<'EOF'
const tryCall = (label, f) => {
  try { f(); } catch (e) { console.log(`${label.padEnd(22)} ${e.name}: ${e.message}`); }
};
const data = { items: [1, 2, 3] };
tryCall("object, not array", () => data.map((x) => x));
const price = "5";
tryCall("string, not number", () => price.toFixed(2));
const lib = { default: () => "ok" };
tryCall("wrong import shape", () => lib());
let format = (x) => x.trim();
format = "oops";
tryCall("overwritten variable", () => format(" a "));
console.log("fixed:", data.items.map((x) => x * 2), Number(price).toFixed(2), lib.default());
EOF
node cases.js

Output

object, not array      TypeError: data.map is not a function
string, not number     TypeError: price.toFixed is not a function
wrong import shape     TypeError: lib is not a function
overwritten variable   TypeError: format is not a function
fixed: [ 2, 4, 6 ] 5.00 ok

Fixes

  • Typo or wrong object: console.log(Object.keys(obj)) shows which methods exist. Methods defined on a class live on its prototype, so obj.method is undefined when obj is a plain JSON object rather than a class instance.
  • Array methods on non-arrays: API responses often wrap the array (response.items, response.data). DOM querySelectorAll returns a NodeList, which has forEach but not map: use Array.from(list).map(...).
  • Imports: import fn from "./mod.js" reads the default export; import { fn } from "./mod.js" reads a named one. With CommonJS interop, the function may be on .default.
  • Optional callbacks: options.onDone?.() calls the function only if it exists.

Sources