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

Make the transition to Node.js if you are a Java, PHP, Rails or .NET developer with these resources to help jumpstart your Node.js knowledge plus pick up some development tips.  Brought to you in partnership with IBM.

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 ~

Learn why developers are gravitating towards Node and its ability to retain and leverage the skills of JavaScript developers and the ability to deliver projects faster than other languages can.  Brought to you in partnership with IBM.

Topics:

Published at DZone with permission of Stoimen Popov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}