SyntaxError: missing ; before statement - JavaScript 编辑

The JavaScript exception "missing ; before statement" occurs when there is a semicolon (;) missing somewhere and can't be added by automatic semicolon insertion (ASI). You need to provide a semicolon, so that JavaScript can parse the source code correctly.

Message

SyntaxError: Expected ';' (Edge)
SyntaxError: missing ; before statement (Firefox)

Error type

SyntaxError.

What went wrong?

There is a semicolon (;) missing somewhere. JavaScript statements must be terminated with semicolons. Some of them are affected by automatic semicolon insertion (ASI), but in this case you need to provide a semicolon, so that JavaScript can parse the source code correctly.

However, oftentimes, this error is only a consequence of another error, like not escaping strings properly, or using var wrongly. You might also have too many parenthesis somewhere. Carefully check the syntax when this error is thrown.

Examples

Unescaped strings

This error can occur easily when not escaping strings properly and the JavaScript engine is expecting the end of your string already. For example:

var foo = 'Tom's bar';
// SyntaxError: missing ; before statement

You can use double quotes, or escape the apostrophe:

var foo = "Tom's bar";
var foo = 'Tom\'s bar';

Declaring properties with var

You cannot declare properties of an object or array with a var declaration.

var obj = {};
var obj.foo = 'hi'; // SyntaxError missing ; before statement

var array = [];
var array[0] = 'there'; // SyntaxError missing ; before statement

Instead, omit the var keyword:

var obj = {};
obj.foo = 'hi';

var array = [];
array[0] = 'there';

Bad keywords

If you come from another programming language, it is also common to use keywords that don't mean the same or have no meaning at all in javaScript:

def print(info){
  console.log(info);
}; // SyntaxError missing ; before statement

Instead, use function instead of def:

function print(info){
  console.log(info);
};

See also

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

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

发布评论

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

词条统计

浏览:85 次

字数:3947

最后编辑:7年前

编辑次数:0 次

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