JavaScript Objects Coding Style

JavaScript vs. PHP

Continuing from my post about PHP arrays coding style and following the comments of that post, I’d like to write a bit about JavaScript objects’ coding style.

You perhaps know that the term object is quite undefined or under estimated in the JavaScript world, but I’d speak about the key/value pairs in JS commonly formatted like that:

var obj = { key : 'value' }

Here you can add more and more key/value pairs, but what’s different from the PHP associative arrays and what’s the same and should be cosidered.

The Same as PHP?

I wrote about the alignment in PHP and hashes. Than I showed how I align them:

$arr = array(
   'short'   => 'val',
   'longkey' => 'val'
);

In JavaScript you should use the same technique of alignment:

var obj = {
   'short'   : 'val',
   'longkey' : 'val'
};

Some Differences

Yes, there are more differences, which is normal. First of all you don’t have the => notation in JavaScript and a : is used. Second and most important you cannot add a trailing comma after the last key/value pair. Note that in PHP that’s fine!

// that will throw an error in MSIE
var obj = {
   'short'   : 'val',
   'longkey' : 'val',
};

while this is OK in PHP and it’s encouraged:

$arr = array(
   'short'   => 'val',
   'longkey' => 'val',
);

One thought on “JavaScript Objects Coding Style

  1. How about doing away with the worry of adding , after each element.

    Why not try this:

    PHP:

    Single dimensional-
    $arr['short']  = 'val';
    $arr['longkey'] = 'val';

    Multi dimensional-

    $arr[0][0]='00';
    $arr[0][1]='01';
    $arr[1][0]='10';
    $arr[1][1]='11';

    This looks neat,structured & easy to understand what key holds what value.

Leave a Reply

Your email address will not be published. Required fields are marked *