Objects for Structured Data

Course: JavaScript Beginner

Lesson 12: Objects for Structured Data

Level

Beginner

Estimated Reading Time

10–15 minutes

Goal

By the end of this lesson, the learner will be able to:

  • Create object literals and access properties using dot and bracket notation
  • Add, update, and delete properties on an object
  • Loop over an object's keys using Object.keys() and for...in

Frontend Development Context

When you work with real data in frontend development, it rarely comes as a single value. A user has a name, an email, an avatar, a role, and a subscription tier. A product has a name, a price, a category, a stock count, and a thumbnail URL. Objects let you group all of these related values under one name, so you can pass them around your code as a single unit instead of managing a dozen separate variables.

Most data from APIs arrives as JSON, which maps directly to JavaScript objects. Understanding how to read, navigate, and update objects is fundamental to using API data in your UI — whether you are rendering a user profile card, populating a form, or displaying search results.

Explanation

An object literal is created with curly braces and contains one or more key-value pairs. Keys are strings (or can be written without quotes if they are valid identifiers), and values can be any type — strings, numbers, booleans, arrays, other objects, or functions.

Dot notation accesses a property by name: user.name. It is clean and readable and is the standard way to access known keys. Bracket notation accesses a property using a string or expression in brackets: user["name"] or user[dynamicKey]. Bracket notation is necessary when the property name is stored in a variable, contains special characters, or is determined at runtime.

You can add a new property to an object by simply assigning to it: user.age = 30. You can update an existing property the same way. You can delete a property using the delete keyword: delete user.age.

Object.keys(obj) returns an array of the object's own property names (keys). This is useful for iterating over an object's properties. The for...in loop also iterates over an object's enumerable properties.

Objects can be nested — an object can have a property whose value is another object. Accessing nested properties uses chained dot notation: user.address.city. When nesting, be careful about accessing properties that might not exist — using optional chaining ?. prevents errors when a nested property is absent.

Code Example

This example creates a user profile object, reads its properties, adds a new one, and renders a summary to the DOM:

const user = {
  username: "sarah_codes",
  email: "[email protected]",
  role: "editor",
  stats: {
    postsWritten: 14,
    followers: 320,
  },
};

// Access properties
console.log(user.username);           // "sarah_codes"
console.log(user.stats.postsWritten); // 14

// Add a new property
user.isVerified = true;

// Update an existing property
user.role = "admin";

// Access with bracket notation (dynamic key)
const field = "email";
console.log(user[field]); // "[email protected]"

// Render a summary
const keys = Object.keys(user);
console.log(`Profile has ${keys.length} top-level fields`);

document.querySelector("#profile-name").textContent = user.username;

Code Explanation

The user object uses dot notation to access username and the nested stats.postsWritten. Nesting objects inside objects is natural — here stats groups numeric data that belongs together. Accessing a nested property requires two dots: user.stats.postsWritten.

Adding user.isVerified = true creates a new property on the object. This is how objects grow in response to data. Updating user.role = "admin" replaces the existing "editor" value. Both operations use the same syntax — assignment to a property path.

The bracket notation example shows how to use a variable as the property name. user[field] is equivalent to user.email when field is "email". This is essential when building dynamic UIs where you need to look up a property based on user input or a loop variable.

Object.keys(user) returns ["username", "email", "role", "stats", "isVerified"] — an array of all the top-level keys. The length tells you how many top-level fields the object has. This pattern is used to inspect objects, build tables, or iterate over form field configurations.

Pattern Highlights

Positive Pattern: Use dot notation for known, static keys — it is the clearest way to read an object's properties. Switch to bracket notation only when the key is dynamic or stored in a variable.

⚠️ Neutral Note: Objects in JavaScript are passed by reference, not by value. If you pass an object to a function and modify its properties, the original object is changed. Use { ...obj } (spread) to make a shallow copy when needed.

Negative Pattern: Using many separate variables to represent the same concept (userName, userEmail, userRole) when they all belong to one user object makes code harder to pass around and maintain.

Common Mistakes

Mistake 1: Accessing a deeply nested property without checking if intermediate properties exist

Accessing user.address.city throws an error if user.address is undefined.

const user = { name: "Alex" }; // no address property

console.log(user.address.city); // TypeError: Cannot read properties of undefined

Use optional chaining to safely navigate: user?.address?.city returns undefined instead of throwing an error when address is missing.

Mistake 2: Confusing Object.keys() with the values

Object.keys() returns the keys (property names) as an array of strings — not the values.

const product = { name: "Chair", price: 199, inStock: true };

console.log(Object.keys(product));   // ["name", "price", "inStock"]
console.log(Object.values(product)); // ["Chair", 199, true]

If you need the values, use Object.values(). If you need both, use Object.entries(), which returns an array of [key, value] pairs.

Mistake 3: Using delete when you mean to set a value to empty

delete obj.property removes the property entirely, which can cause undefined errors if code later expects the property to exist. Often, setting the value to null or an empty string is safer.

const session = { userId: 42, token: "abc123" };

delete session.token; // property is gone
console.log("token" in session); // false — the key no longer exists

// Often safer:
session.token = null; // key still exists, value is empty

Use delete when you genuinely want to remove a property. Use null or "" when you want the property to exist but represent "no value".

Quick Recap

  • Objects group related data as key-value pairs; access properties with dot notation (obj.key) or bracket notation (obj["key"])
  • Add properties by assignment (obj.newKey = value); update the same way; remove with delete obj.key
  • Object.keys(obj) returns an array of keys; Object.values(obj) returns an array of values
  • Use optional chaining (?.) when accessing nested properties that might not exist to avoid TypeErrors

Ready to test your understanding? Take the quiz to reinforce what you learned.

© 2026 Ant Skillsv.26.07.07-23:01