Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"," at the end of a single element in a object in javascript is illegal?

Tags:

javascript

I wonder why putting a comma at the end of a single element is legal in a JavaScript array:

var array = [
    'foo', // no error in IDE
]

while putting it at the end of a single element in an object is illegal (at least my IDE - WebStorm - is flagging about an error):

var object = {
    'foo': 'bar', // error in IDE
}

Is this really illegal in JavaScript?

like image 860
ajsie Avatar asked Nov 07 '10 02:11

ajsie


3 Answers

In the ECMAScript 5 specification it is legal:

ObjectLiteral : 
    { } 
    { PropertyNameAndValueList } 
    { PropertyNameAndValueList , } 

It was illegal in ECMAScript 3.

ObjectLiteral : 
    { } 
    { PropertyNameAndValueList } 

I believe it was made legal to make things like this doable.

function getItems() {
    return {
        one : 1,
        two : 2,
        three : 3,
        //four : 4,
    };
}

Instead of this:

function getItems() {
    return {
        one : 1,
        two : 2,
        three : 3//,
        //four : 4,
    };
}

Saving some of the programmers time.

like image 111
ChaosPandion Avatar answered Oct 04 '22 13:10

ChaosPandion


In addition to what ChaosPandion mentioned, there's an important difference between a , at the end of an object and an array. Empty commas in an array (technically called elisions) insert undefined elements at the corresponding position; this increases the length of the array but the values are undefined.

Edit: Thanks to ChaosPandion and CMS for pointing out the error. I just reread the specs and indeed a single trailing comma does not increase the length, however any additional trailing commas or any commas in the middle of an array will increase the length.

For example, [ 1,2,, ] is an array of length 3 and the same as [ 1, 2, undefined ]. Similarly, [ 1,,,2 ] is an array of length 4 and the same as [ 1, undefined, undefined, 2 ].

Strangely enough, when it comes to this "feature" of JavaScript, IE behaves correctly with a trailing comma in an array (it counts the extra element) while Firefox ignores the last undefined element.

like image 39
casablanca Avatar answered Oct 04 '22 14:10

casablanca


Firefox tolerates it, most other sane browsers do so to. Do I still need to mention IE chokes on it?

Anyway, simply ensure there are no commas at the end of arrays/objects. While languages like PHP and - depending on the implementation - JavaScript are fine with it, it is extremely ugly - you also wouldn't leave a string at the end of a file unclosed just because the parser could consider EOF as a valid string end.

like image 38
ThiefMaster Avatar answered Oct 04 '22 14:10

ThiefMaster