Error with hashes in IE but not in Firefox

There’s a common error that happens quite a lot on IE only and never on Firefox. You search it, you check all your variables, you comment your code to the bare minimum but you can never find it.

Stop looking! Here’s the answer.

You probably just forgot a comma (,) at the end of a hash. Here’s an example :

  1. var val = {
  2.   cat:"Mistigri",
  3.   dog:"Rex",
  4.   butler:"Jeeves", // There’s an extra comma
  5. }

You see the extra comma at the string “Jeeves”? This what causes the problem. Firefox handles an extra comma nicely but Internet explorer doesn’t. To correct the error, just write :

  1. var val = {
  2.   cat:"Mistigri",
  3.   dog:"Rex",
  4.   butler:"Jeeves" // There’s no extra comma
  5. }

JSLint to the rescue

Programmieraffe told me about JSLint. You paste your javascript code and it verifies it for you. Not only for extra-commas but everything else.

  • http://amwmedia.com Andrew Worcester

    Can’t tell you how many times I’ve had to fix this!

  • Richard Ayotte

    That’s why I always lead with comas.

    [code lang="js"]
    var val = {
    , cat:"Mistigri"
    , dog:"Rex"
    , butler:"Jeeves"
    }
    [/code]

  • http://www.timmyontime.com Dan Simard

    It happened to me a few days ago even if I know that for years. I will be looking for a tool (or creating one) that will check this!

  • http://www.timmyontime.com Dan Simard

    Hmmm… I don't like to alterate readability when I just could just take care but everyone has their own way of doing things…

  • http://www.timmyontime.com Dan Simard

    It happened to me a few days ago even if I know that for years. I will be looking for a tool (or creating one) that will check this!

  • http://programmieraffe.de/ programmieraffe

    JSLint catches extra commas.

    http://www.jslint.com/

  • http://www.timmyontime.com Dan Simard

    Thanks a lot, I'll edit the post to talk about it.

  • simaopig

    The first comma used error.

    Sorry my Englisth is poor..

  • http://www.timmyontime.com Dan Simard

    You're right, it should have been :

    var val = {
    cat:”Mistigri”
    , dog:”Rex”
    , butler:”Jeeves”
    }

  • http://www.sonnenschutz-tipps.de sonnenschutz-tipps

    I always was wondering about this error in IE. You have got the solution. Brilliant !

  • http://www.hausgarten.net Peter Garten

    Hi. Does this error also occur in IE8? I fixed it in previous versions only.