Over a million developers have joined DZone.

JavaScript Objects Coding Style

DZone's Guide to

JavaScript Objects Coding Style

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.


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

Opinions expressed by DZone contributors are their own.


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.


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

{{ parent.tldr }}

{{ parent.urlSource.name }}