Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Coding Style Reviewed

DZone's Guide to

Coding Style Reviewed

· Web Dev Zone ·
Free Resource

Have you seen our HERE Twitch channel to livestream our Developer Waypoints series?

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.

Related posts:

  1. PHP Associative Arrays Coding Style
  2. JavaScript Objects Coding Style
  3. PHP: Conditionals Coding Style

~ End Article and Begin Conversation ~

There are no comments yet...

~ Now It's Your Turn ~

Developer Waypoints is a live coding series from HERE, which will teach you how to build with maps and location data.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}