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' } |
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'
); |
$arr = array(
'short' => 'val',
'longkey' => 'val'
);
In JavaScript you should use the same technique of alignment:
var obj = {
'short' : 'val',
'longkey' : 'val'
}; |
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',
}; |
// 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',
); |
$arr = array(
'short' => 'val',
'longkey' => 'val',
);