Borislav Hadzhiev
Reading time·2 min
Photo from Unsplash
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.
Here's an example of how the error occurs.
// ⛔️ SyntaxError: Function statements require a function name function(){};
This is a statement and not an expression, so we have to give the statement a name.
// ✅ Works function example() { return 2 + 2; } console.log(example()); // 👉️ 4
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 the function in parentheses and added another set of parentheses after, where we passed arguments 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, 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 to the object and they don't 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.