Fix Function statements require a Function name Error in JS


Borislav Hadzhiev

Tue Oct 19 20212 min read


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.

// ⛔️ Function statements require a function name function(){};

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

// ✅ 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.

(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.

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.

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.

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.