The braces { }
will construct an object using the object literal notation. You are not constructing an array, but an object, even though JavaScript objects can also be thought of as associative arrays.
Further reading:
Apart from the few primitive types (numbers, strings, booleans, null and undefined) everything is an object in JavaScript (even functions).
Objects are basically containers of properties, which happen to be very useful for collecting and organizing data.
The object literal notation (the braces { }
method that you describe) is very handy for creating objects:
var myFirstObject = {
'name': 'Bobby',
'surname': 'Smith'
};
The quotes around property names are optional if the name would be a legal JavaScript identifier and not a reserved word. That is why 'choices[]'
is quoted in your example, because it is not a legal JavaScript identifier. A property's name can be any string as long as it is quoted.
Objects can also contain other objects, so they can easily represent trees or graphs:
var myFlight = {
'airline': 'Airline Name',
'number': 'AN700',
'departure': {
'IATA': 'SYD',
'time': '2010-09-04 23:10:00'
},
'arrival': {
'IATA': 'LAX',
'time': '2010-09-05 05:14:00'
}
};
JavaScript objects also happen to be a convenient hash table data structure, and can be used as associative arrays as mentioned earlier. You could easily do the following:
var myHashTable = {};
myHashTable['name'] = 'Bobby';
myHashTable['surname'] = 'Smith';
// subscript notation:
alert(myHashTable['name'] + ' ' + myHashTable['surname']);
// dot notation: (equivalent)
alert(myHashTable.name + ' ' + myHashTable.surname);