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

JavaScript Objects Coding Style

DZone's Guide to

JavaScript Objects Coding Style

· Web Dev Zone
Free Resource

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

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',
);



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

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 DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}