The woes of trailing commas in IE

This post was published in 2012 and is kept here for reference. It may contain information that's outdated or inaccurate.

If you leave a trailing comma in your JavaScript code, you’re a terrible person. It’s right up there with omitting semicolons as far as I’m concerned.

While fixing some issues on a site in IE7 recently, I was greeted by the familiarly unhelpful error message from Internet Explorer 7 that prompted me to write this.

Error: Expected identifier, string or number

You can see an example below:

What does that tell us? Bugger all in fact, unless you’ve tackled this problem before. It’s really unhelpful, but it’s caused by having a trailing comma inside an array/object/method, like the following:

forms.set_errors(
    $form,
    response.form_errors || [],
    response.field_errors,
);

That right there, that’s not cool. It’ll make Internet Explorer explode.

If you had any consideration you would write something more like:

forms.set_errors(
    $form,
    response.form_errors || [],
    response.field_errors
);

tasty.

You can prevent this problem occuring by using a linter, or you can retroactively go and find the problem-causing lines in your JavaScript using a RegEx pattern such as the following:

,[\s\n]*[^\[\{\w\n\s/\*\"\'\$\#\.\`\:\|\!]

Though this is valid according to ECMAScript 5, it’s another one of those bodged features in Internet Explorer that happens to behave unlike every other browser, so I think it’s best to go for the solution that works for everybody.

That’s about all I’ve got to say, I just wanted to rant about this and how terrible IE7 is.

This post is also available in plain text

[Comments]

Want to comment? You can do so via Github.
Comments via Github are currently closed.

[Webmentions]

Want to reply? I've hooked up Webmentions, so give it a go!