What is the "Function statement requires a name" syntax error?

The JavaScript exception SyntaxError - Function statement requires a name occurs when a function statement (or function declaration) requires a name but is not given one.

The SyntaxError object represents an error when trying to interpret syntactically invalid code. It is thrown when the JavaScript engine encounters tokens or a token order that does not conform to the syntax of the language when parsing code.

Instance Properties

  • SyntaxError.prototype.message: Error message. Although ECMA-262 specifies that SyntaxError should provide its own message property, in SpiderMonkey it inherits Error.prototype.message.

  • SyntaxError.prototype.name: Error name. This is inherited from Error.

  • SyntaxError.prototype.fileName: Path to file that raised this error. This is inherited from Error.

  • SyntaxError.prototype.lineNumber: Line number in file that raised this error. Inherited from Error.

  • SyntaxError.prototype.columnNumber: Column number in line that raised this error. This is inherited from Error.

  • SyntaxError.prototype.stack: Stack trace. This is inherited from Error.

Code

There is a function statement in the below code that is unnamed but requires a name, which will yield a SyntaxError. We will need to check how functions are defined and if we need to provide a name for it, if the function in question needs to be a function expression, or if the function code is placed correctly in the used context.

function () {
return 'Hello world';
}
// SyntaxError: function statement requires a name

In order to solve this, we can use a function expression (assignment) instead. Basically, we will assign a name to our anonymous function.

let greet = function() {
return 'Good Morning';
};
console.log(greet())