You create an object with curly braces { }. Inside, you write key: value pairs, separated by commas:
const phone = {
brand: "Nova",
model: "Spark",
storageGB: 128,
colors: ["black", "blue", "gold"],
isWaterproof: false,
};
console.log(phone);
It prints
{
brand: 'Nova',
model: 'Spark',
storageGB: 128,
colors: [ 'black', 'blue', 'gold' ],
isWaterproof: false
}(Node prints short objects on one line and longer ones spread across several lines. Either way, it's the same object.)
A few rules:
- Each key is followed by a colon
:, then the value. - Properties are separated by commas. A comma after the last property is allowed (and helpful, because adding a new property later won't require touching the line above).
- Values can be anything: strings, numbers, booleans, arrays, other objects, even functions.
- Keys follow the same rules as variable names. If you really need a key with a space or a hyphen, wrap it in quotes:
"favorite color": "green". But it's much easier to just use camelCase.
An empty object is simply {}.