"Illegal invocation" in JavaScript — What It Means and How to Fix It

What the JavaScript error "Illegal invocation" means and how to fix it.

Published October 30, 2026

Browser built-in functions need to be called with the correct this. Detaching them from their object makes this wrong.

What it means and why it happens

Typical causes: storing document.querySelector in a variable, or passing console.log, fetch or alert unbound.

Read the full message: it names the file and line where the problem was detected, which is the best place to start.

What you see

run the code
TypeError: Illegal invocation

Practical examples

Code that triggers it

const q = document.querySelector
q('#id')

The fix

const q = document.querySelector.bind(document)
q('#id')
// or
const fetchFn = (...a) => fetch(...a)

Arrow wrapper

const log = (...a) => console.log(...a)

Common mistakes

  • Detaching DOM methods.
  • Passing window methods as callbacks unbound.
  • Assigning native methods to objects.

Key takeaways

  • TypeError: Illegal invocation: Browser built-in functions need to be called with the correct this.
  • Read the message and the line number first.
  • Fix the cause, don't just silence the error.

FAQ

How to fix quickly?

bind() the method or wrap it in an arrow function.

How do I find which line caused TypeError: Illegal invocation?

The error message and stack trace show the file and line; start there and work backwards.

More JavaScript articles