Over a million developers have joined DZone.

Coding Style Reviewed

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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 ~

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


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.

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.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}