SyntaxError: function statement requires a name - JavaScript 编辑

The JavaScript exception "function statement requires a name" occurs when there is a function statement in the code that requires a name.

Message

Syntax Error: Expected identifier (Edge)
SyntaxError: function statement requires a name [Firefox]
SyntaxError: Unexpected token ( [Chrome]

Error type

SyntaxError

What went wrong?

There is a function statement in the code that requires a name. You'll need to check how functions are defined and if you need to provide a name for it, or if the function in question needs to be a function expression, an IIFE, or if the function code is placed correctly in this context at all.

Examples

Statements vs expressions

A function statement (or function declaration) requires a name, this won't work:

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

You can use a function expression (assignment) instead:

var greet = function() {
  return 'Hello world';
};

Or, you function is maybe intended to be an IIFE (Immediately Invoked Function Expression), which is a function that runs as soon as it is defined. You will need a few more braces in this case:

(function () {

})();

Labeled functions

If you are using function labels, you will still need to provide a function name after the function keyword. This doesn't work:

function Greeter() {
  german: function () {
    return "Moin";
  }
}
// SyntaxError: function statement requires a name

This would work, for example:

function Greeter() {
  german: function g() {
    return "Moin";
  }
}

Object methods

If you intended to create a method of an object, you will need to create an object. The following syntax without a name after the function keyword is valid then.

var greeter = {
  german: function () {
    return "Moin";
  }
};

Callback syntax

Also, check your syntax when using callbacks. Brackets and commas can get difficult easily.

promise.then(
  function() {
    console.log("success");
  });
  function() {
    console.log("error");
}
// SyntaxError: function statement requires a name

Correct would be:

promise.then(
  function() {
    console.log("success");
  },
  function() {
    console.log("error");
  }
);

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:52 次

字数:4929

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文