Skip to content

How to solve the "is not a function" error in JavaScript

New Course Coming Soon:

Get Really Good at Git

I write JavaScript without semicolons.

And I really like that. The language is cleaner, in my opinion.

You might not like that, and it’s understandable. But that’s the way it is.

Semicolons are optional. We are not required to add them.

Sometimes, however, we must pay attention. In particular, in Node.js we use require() to load external modules and files.

This can cause, in some cases, an error like this:

TypeError: require(...) is not a function

That’s a weird error, right?

Let’s look at how I got it.

I required a library, and then I had to run some code at the root level and I created an immediately-invoked async function:

const fs = require('fs')

(async () => {
  //...
})()

JS does not see a semicolon after require(), and we start a line with a (, and JS thinks we’re trying to execute a function.

It consider require('fs') as the name of the function, which is something that could actually work if the module export returned a function.

But it’s not, so we get that ...is not a function error.

How do we fix it?

We must add a semicolon. Somewhere.

This would work:

const fs = require('fs')

;(async () => {
  //...
})()

and also this would work:

const fs = require('fs');

(async () => {
  //...
})()

It’s a little price we have to pay to avoid the use of semicolons everywhere.

Tip: top-level await is now a thing, you can use that instead of this structure, and it will prevent such errors.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: