Objects
Objects store data as named key/value pairs.
Syntax
let obj = { key: value };An object stores data as key/value pairs (called properties). Write it with curly braces.
Accessing properties
- Dot notation:
person.name. - Bracket notation:
person['name']— needed when the key is stored in a variable.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Model a user account with properties like id, email, and role in a single structured value.
- Group related configuration settings into one object to pass to a third-party SDK initialiser.
- Represent a product in a catalogue with name, price, and stock count as named properties.
More examples
Declare and read an object
Declares a plain object and accesses properties via dot notation and bracket notation.
const user = {
id: 1,
name: "Alice",
email: "[email protected]",
active: true
};
console.log(user.name); // "Alice"
console.log(user["id"]); // 1Nested object
Shows a nested object where the price property is itself an object with amount and currency fields.
const product = {
id: 42,
name: "Laptop",
price: { amount: 999, currency: "USD" }
};
console.log(product.price.amount); // 999Add and delete properties
Adds new properties to an existing object and removes one with the delete operator.
const config = { timeout: 3000 };
config.retries = 3;
config.debug = true;
delete config.debug;
console.log(config); // { timeout: 3000, retries: 3 }
Discussion