Skip to content

Instantly share code, notes, and snippets.

@Wizek
Created February 18, 2012 10:29
Show Gist options
  • Save Wizek/1858647 to your computer and use it in GitHub Desktop.
Save Wizek/1858647 to your computer and use it in GitHub Desktop.
JS Object literal syntax
/*\
* Journey in search of the most beautiful and
* most usable JavaScript object literal syntax.
\*/
/*\
* Traditional, AKA how fast can you find a missing comma?
\*/
var temp = {
Baar: 1,
Foo: 'This is a good day to--fiddle with syntax!',
function: function() {
return Math.round(3-2.2)
},
object: {
keys: true,
values: true
},
arrayShort: [1, 2],
arrayLong: [
123,
124,
125
],
arrayLongLong: [
[
123,
124
],
[
125,
126
]
],
'Another key': new Date
}
/*\
* Pre-comma: Easier to see missing commas
* , but there is always a gap at the first line
* , which makes you think of syntax error in vein
* , and it doubles the indentations needed
* , and it also hinders code folding in some editors (due to gap)
\*/
var temp = {
Baar: 1
, Foo: 'This is a good day to--fiddle with syntax!'
, function: function() {
return Math.round(3-2.2)
}
, object: {
keys: true
, values: true
}
, arrayShort: [1, 2]
, arrayLong: [
123
, 124
, 125
]
, arrayLongLong: [
[
123
, 124
]
, [
125
, 126
]
]
, 'Another key': new Date
}
/*\
* Start object on new line:
* + Succinct, no unnecessary indentation (maybe 1 at the beginning)
* + No gap, good for your health, and your code folding.
* - Maybe too succinct, arrayLongLong may be hard to follow
* - Inconsistent with other code segments where the closing paren is
* at the base of the expression (in this case `var temp =`)
\*/
var temp =
{ Baar: 1
, Foo: 'This is a good day to--fiddle with syntax!'
, function: function() {
return Math.round(3-2.2)
}
, object:
{ keys: true
, values: true
}
, arrayShort: [1, 2]
, arrayLong:
[ 123
, 124
, 125
]
, arrayLongLong:
[
[ 123
, 124
]
, [ 125
, 126
]
]
, 'Another key': new Date
}
// It also makes for some very interesting patterns in some cases
var temp =
{ foo1:
{ bar1:
{ baz1: 1
, baz2: 1
, baz3: 1
}
, bar2: 1
, bar3: 1
}
, foo2: 1
, foo3: 1
}
var temp =
[ [ [ 1
, 2
]
, 3
, 4
]
, 5
, 6
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment