Definition
You create an object using curly brackets. You can also directly include some entries. For that, state the key first, followed by a colon and the value.
const emptyObject = {};
const obj = {
favoriteNumber: 42,
greeting: 'Hello World',
useGreeting: true,
address: {
street: 'Trincomalee Highway',
city: 'Batticaloa',
},
fruits: ['melon', 'papaya'],
addNumbers: function (a, b) {
return a + b;
},
};
The trailing comma after the last entry is optional in JavaScript.
If the key follows the naming rules for a JavaScript identifier, you can omit the quotation marks. For keys with special characters in the name, you need to use the usual string notation.
const obj = {
'1keyStartsWithNumber': '...',
'key/with/slashes': '...',
'key-with-dashes': '...',
'key with spaces': '...',
'#&()[]{}èä樹keyWithSpecialChars': '...',
};
Backlinks