JS Objects
Once I posted about JavaScript object coding style. Back than I made the analogy with PHP array coding style. In breve it’s useful to format the arrays in PHP simply like that:
$data = array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', ); |
Note that there is a trailing comma after the last key/value pair. This is not a syntax error and helps you add new elements to the array with no fear to forget the comma. This coding standard is quite well known in the PHP community, but in fact writing JavaScript objects can be “translated” to something very similar. The only problem is that the trailing comma in JavaScript will result to an error, especially in Internet Explorer, so it is important to remove it.
var obj = { key1 : 'value1', key2 : 'value2', key3 : 'value3', key4 : 'value4', key5 : 'value5' }; |
The problem is that when you’ve to add one key/value pair, you’ve to add the comma after the last pair. This actually makes it useless.
Better Solution
There is another way, much better I think, that may help you more when adding new pairs to the object.
var obj = { key1 : 'value1' , key2 : 'value2' , key3 : 'value3' , key4 : 'value4' , key5 : 'value5' }; |
In this example you can simply copy/paste the last pair and change the key and value, or you can simply can continue writing the way the object is constructed.
Thus you don’t have the problem with the last comma and syntax errors.