Object literals

An object is a collection of key-value pairs. Each key is a property name, and each value can be any JavaScript type — a string, number, boolean, array, or even another object. In UrbanCart, every product, user, and order is represented as an object.

🎧
UrbanCart Example
A product in the catalog is an object with name, price, and stock status

When UrbanCart loads a product page, it fetches an object from the server that contains every detail about that product — its name, price, whether it's in stock, its category, and more. Objects are the natural shape of structured data in JavaScript.

You create an object using curly braces {}. This is called an object literal:

objects.js Object Literals
Output
{ "name": "Wireless Headphones", "price": 2499, "inStock": true } { "firstName": "Amara", "lastName": "Okafor", "email": "amara@example.com", "city": "Nairobi" } {}
Objects vs. arrays: Arrays are ordered lists accessed by index (cart[0]). Objects are named collections accessed by key (product.name). Use arrays for lists of similar things. Use objects when each piece of data has a name.

Dot vs bracket notation

There are two ways to access and set object properties: dot notation and bracket notation. Both work, but each has specific use cases.

🔵

Dot notation

product.name
Clean and readable. Use when the property name is a valid identifier and you know it ahead of time.

🟡

Bracket notation

product["name"]
Flexible. Use when the property name is dynamic, stored in a variable, or contains special characters.

access.js Dot & Bracket
Output
Wireless Headphones 2499 Wireless Headphones 2499 UrbanAudio true 4.5 128
Rule of thumb: Use dot notation by default — it's cleaner. Switch to bracket notation when the key is dynamic (from a variable), contains special characters (hyphens, spaces), or when you're iterating over keys.

Methods

A method is a function that lives inside an object. Methods let objects do things — not just hold data. In UrbanCart, a cart object doesn't just store items; it can add items, remove items, and calculate totals.

methods.js Object Methods
Output
Wireless Headphones added to cart USB-C Hub added to cart Laptop Stand added to cart Items in cart: 3 Cart total: 4897
Shorthand method syntax: Writing addItem(item) { ... } is the modern shorthand. The older syntax is addItem: function(item) { ... }. Both work the same way, but the shorthand is cleaner and preferred in modern JavaScript.

The this keyword

Inside a method, this refers to the object the method belongs to. It's how a method accesses the object's own properties and other methods.

this.js this Keyword
Output
Mechanical Keyboard — KES 3499 Order ORD-2047 has 2 items Arrow this.id: undefined
Arrow function caveat: Arrow functions do not have their own this. They inherit this from the surrounding scope. That's why order.brokenSummary() can't access this.id — the arrow function's this points to the outer scope (usually window or undefined in strict mode), not the order object. Always use regular functions for object methods.

Destructuring

Object destructuring lets you unpack properties from an object into individual variables. It's clean, readable, and used everywhere in modern JavaScript — especially in React.

destructure.js Object Destructuring
Output
Wireless Headphones 2499 Wireless Headphones 2499 0 0 Wireless Headphones | 2499 | In Stock
Destructuring in function parameters: Instead of accessing product.name, product.price inside a function, you can destructure directly in the parameter list: function display({ name, price }) { ... }. This pattern is extremely common in React components.

Spread operator

The spread operator ... copies all properties from one object into another. It's the cleanest way to create updated copies of objects without mutating the originals — a key concept in React state management.

spread.js Spread Operator
Output
Updated: { "name": "Wireless Headphones", "price": 1999, "inStock": true } Original: { "name": "Wireless Headphones", "price": 2499, "inStock": true } Detailed: { "name": "Wireless Headphones", "price": 2499, "inStock": true, "rating": 4.5, "reviews": 128 } Full: { "name": "Wireless Headphones", "price": 2499, "inStock": true, "weight": "250g", "freeShipping": true } Override: { "name": "Premium Headphones", "price": 3999, "inStock": true }
🛒
UrbanCart Example
Immutable product updates during a flash sale

During a flash sale, UrbanCart creates discounted copies of products using const saleProduct = { ...product, price: salePrice }. The original product data stays intact in the database, while the sale version is displayed to customers. This immutable pattern prevents bugs where sale prices accidentally overwrite regular prices.

Object.keys / values / entries

These three static methods let you iterate over an object's properties. They convert an object into arrays that you can loop through, map, or filter.

🔑

Object.keys()

Returns an array of the object's property names (keys).

📦

Object.values()

Returns an array of the object's property values.

iterate.js Keys, Values, Entries
Output
Keys: ["brand", "type", "wireless", "battery", "weight"] Values: ["UrbanAudio", "Over-Ear", true, "30 hours", "250g"] Entries: [["brand", "UrbanAudio"], ["type", "Over-Ear"], ["wireless", true], ["battery", "30 hours"], ["weight", "250g"]] --- Product Specifications --- brand: UrbanAudio type: Over-Ear wireless: true battery: 30 hours weight: 250g
Why not for...in? You can use for...in to loop over object keys, but it also iterates over inherited properties (from the prototype chain). Object.keys() only returns the object's own properties, which is almost always what you want.

Optional chaining (?.)

When working with nested objects, accessing a deeply nested property can throw an error if any part of the chain is undefined or null. The optional chaining operator ?. safely accesses nested properties — returning undefined instead of crashing.

optional.js Optional Chaining
Output
Nairobi undefined shipped undefined City not provided
When to use ?. Use optional chaining when accessing data from APIs, user input, or any source where a property might be missing. It's especially useful in UrbanCart when displaying order details — a guest user might not have a saved address, and user?.address?.city handles that gracefully without crashing the page.

Try It Yourself #1 — Product & Cart objects

Build a Product object and a Cart object with methods (addItem, removeItem, getTotal). Edit the code and click Run to see the output.

Try It Yourself — Product & Cart with Methods
Output

Try It Yourself #2 — Destructuring & spread

Use destructuring to extract properties and the spread operator to create updated product copies. Edit the code and click Run to see the output.

Try It Yourself — Destructuring & Spread
Output

Test your knowledge

Question 1 of 5
How do you access a property whose key is stored in a variable?
Question 2 of 5
Why should you NOT use arrow functions as object methods?
Question 3 of 5
What does const { name: productName } = product do?
Question 4 of 5
What does { ...product, price: 1999 } create?
Question 5 of 5
What does user?.address?.city return when the user has no address property?
0
/5
Great job!
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

You just mastered JavaScript objects.
Now build a full-stack career.

Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses →