Fix Function statements require a Function name Error in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Hiva Sharifi

Fix Function statements require a Function name Error #

The "Function statements require a function name" error occurs when we have a function statement to which we haven't assigned a name. To solve the error, use an immediately invoked function expression, e.g. (function() {})() or assign a name to the statement.

syntaxerror function statements require function name

Here's an example of how the error occurs.

index.js
// โ›”๏ธ Function statements require a function name function(){};

This is a statement not an expression, so we have to give the statement a name.

index.js
// โœ… Works function example() { }

Alternatively, you could define an immediately invoked function expression if you want to invoke a nameless function immediately after the script loads.

index.js
(function (a, b) { console.log(a + b); // ๐Ÿ‘‰๏ธ 20 })(10, 10);

We had to wrap our function in parenthesis and add another set of parenthesis after, where we are able to pass parameters to the function.

You can also use a function expression.

index.js
const sum = function (a, b) { return a + b; }; console.log(sum(5, 10)); // ๐Ÿ‘‰๏ธ 15

If you don't want to expose one or more functions directly to the global scope, you can add them to an object or a class.

index.js
const obj = { sum(a, b) { return a + b; }, log(message) { console.log(message); }, // ... }; console.log(obj.sum(10, 10)); // ๐Ÿ‘‰๏ธ 20

We can add as many functions as necessary in the object and they do not pollute the global scope.

An even better solution would be to use a class.

index.js
class Person { constructor(first, last) { this.first = first; this.last = last; } getName() { return `${this.first} ${this.last}`; } } const p = new Person('James', 'Doe'); console.log(p.getName()); // ๐Ÿ‘‰๏ธ "James Doe"

A class serves as a container for related functionality. You can add as many methods to it as necessary and they will be accessible on instances of the class.

This solution also allows us to store methods without polluting the global scope.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee