SyntaxError: missing variable name - JavaScript 编辑

The JavaScript exception "missing variable name" occurs way too often as naming things is so hard. Or maybe a comma is wrong. Check for typos!

Message

SyntaxError: missing variable name (Firefox)
SyntaxError: Unexpected token = (Chrome)

Error type

SyntaxError

What went wrong?

A variable is missing a name. This is likely due to a syntax error in your code. Probably a comma is wrong somewhere or you struggled with coming up with a name. Totally understandable! Naming things is so hard.

  • Check to ensure the previous lines / declaration does not end with a comma instead of a semi-colon.

Examples

Missing a variable name

var = "foo";

It's tough coming up with good variable names. We all have been there.

var ohGodWhy = "foo";

Reserved keywords can't be variable names

There are a few variable names that are reserved keywords. You can't use these. Sorry :(

var debugger = "whoop";
// SyntaxError: missing variable name

Declaring multiple variables

Pay special attention to commas when declaring multiple variables. Is there an excess comma? Did you accidentally add commas instead of semicolons?

var x, y = "foo",
var x, = "foo"

var first = document.getElementById('one'),
var second = document.getElementById('two'),

// SyntaxError: missing variable name

The fixed version:

var x, y = "foo";
var x = "foo";

var first = document.getElementById('one');
var second = document.getElementById('two');

Arrays

Array literals in JavaScript need square brackets around the values. This won't work:

var arr = 1,2,3,4,5;
// SyntaxError: missing variable name

This would be correct:

var arr = [1,2,3,4,5];

See also

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

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

发布评论

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

词条统计

浏览:83 次

字数:3829

最后编辑:6 年前

编辑次数:0 次

更多

友情链接

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