Himanshu SharmaSoftware engineer
Let’s talk

JavaScript · Lesson 32 of 58

Objects

Group related data in JavaScript objects. Create them, read and change properties with dot and bracket notation, loop over keys and copy them safely.

15 minArrays and objectsUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonCreate objects, read, add, change and delete properties, loop over keys and values, and explain why objects are shared by reference.

After this lesson you can model real things, such as a user, a product or a setting, as one tidy object, read and change its parts, and loop over everything inside it.

What an object is

An array stores items by position. An object stores values by name. Each name is a key, each stored value is a value, and a key and value together are called a property.

javascript
const user = {
  name: "Asha",
  age: 25,
  isAdmin: false,
  skills: ["html", "css"],
};

Keys are strings (you can drop the quotes when the key is a simple word). Values can be anything: numbers, text, arrays, even other objects or functions. Use an object when you have a handful of named facts about one thing; use an array for a list of many similar things.

Reading properties

javascript
console.log(user.name);          // Asha
console.log(user["age"]);        // 25
console.log(user.skills[0]);     // html
console.log(user.email);         // undefined, no such property

const key = "name";
console.log(user[key]);          // Asha, the key comes from a variable
console.log(user.key);           // undefined, looks for a property called "key"

Dot notation (user.name) is shorter and is the usual choice. Bracket notation (user["name"]) is needed when the key is held in a variable, or contains spaces or dashes, such as data["first-name"].

Reading a missing property does not throw; it gives undefined. But reading a property of undefined does throw, as in user.address.city when there is no address. Optional chaining, user.address?.city, stops and returns undefined instead. It is covered further in optional chaining and other modern syntax.

Adding, changing and deleting

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  const book = { title: "Notes", pages: 120 };
  book.pages = 150;            // change
  book.author = "Unknown";     // add
  delete book.title;           // remove
  log(JSON.stringify(book));
  log("has author?", "author" in book);
  log("has title?", "title" in book);
</script>

Just like arrays, an object declared with const can still be changed; const only stops reassigning the variable. The in operator tells you whether a key exists, even if its value is undefined.

You can build keys on the fly with square brackets in the literal: { [field]: value } creates a property whose name is whatever field holds. When a variable already has the name you want, use the shorthand { name, age } instead of { name: name, age: age }.

Looping over an object

Plain objects are not directly loopable with for...of. Convert them to arrays first:

javascript
const stock = { apples: 5, pears: 0, plums: 12 };

console.log(Object.keys(stock));     // [ 'apples', 'pears', 'plums' ]
console.log(Object.values(stock));   // [ 5, 0, 12 ]
console.log(Object.entries(stock));  // [ [ 'apples', 5 ], [ 'pears', 0 ], [ 'plums', 12 ] ]

for (const [fruit, count] of Object.entries(stock)) {
  console.log(fruit, count);
}
// apples 5
// pears 0
// plums 12

The [fruit, count] in the loop is destructuring, which the next lesson explains. Order is mostly the order you wrote the keys, with one catch: keys that look like whole numbers ("1", "42") come first in ascending order. If order matters a lot, consider a Map (see Set and Map).

Objects are references

Exactly as with arrays, a variable holds a reference to the object:

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  const a = { score: 1, tags: ["x"] };
  const b = a;                        // same object
  const shallow = { ...a };           // new object, tags still shared
  const deep = structuredClone(a);    // fully independent

  b.score = 2;
  a.tags.push("y");
  log("a:", JSON.stringify(a));
  log("shallow:", JSON.stringify(shallow));
  log("deep:", JSON.stringify(deep));
</script>

You will see a has score 2 and tags x,y. The shallow copy kept score: 1 (its own property) but sees the new tag, because the array inside is shared. The deep copy is untouched. Remember the rule: spread copies one level; structuredClone copies everything it can, but it cannot copy functions.

To merge objects, spread them together: { ...defaults, ...overrides }. Later keys win when names collide.

Useful helpers

  • Object.assign(target, source) copies properties into target. Spread is usually clearer.
  • Object.freeze(obj) stops further changes, but only at the top level.
  • Object.hasOwn(obj, "key") checks for an own property, safer than in when inherited keys matter.

Objects holding objects

Real data nests. A user object may hold an address object, which holds a city. You reach in step by step with repeated dots, user.address.city, and you can change a nested value the same way. A list of objects, such as products in a shop, is the most common shape you will see in the wild: an array on the outside, and objects with the same property names inside. The array methods you met in the previous lessons, like filter and map, work well on such lists, and the JSON format you will learn soon describes exactly this kind of nested data.

Because nested objects are also references, changing user.address.city changes it for everyone who holds that same address object. This is the shallow copy trap from the previous section again, just one level deeper.

Common mistakes

  • Using dot notation with a variable key, as in user.key instead of user[key].
  • Expecting const to stop changes to the object.
  • Comparing objects with ===, which compares references, so {} === {} is false.
  • Reading deep paths without checking, like user.address.city when address may be missing.
  • Copying with = and then being surprised when the original changes.

Exercise

Create an object for a book with title, author and pages. Add a read property set to false, then change it to true. Finally print every key and value, one per line, using Object.entries.

Show one possible answer
html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  const book = { title: "A Small Book", author: "Someone", pages: 200 };
  book.read = false;
  book.read = true;
  for (const [key, value] of Object.entries(book)) {
    log(key + ":", value);
  }
</script>

Next: destructuring.

Key points

  • An object stores named values, called properties, as key and value pairs inside curly braces.
  • Read with dot notation (user.name) or bracket notation (user[key]) when the key is a variable or has odd characters.
  • Object.keys, Object.values and Object.entries turn an object into arrays you can loop over.
  • Like arrays, objects are references, so copy with spread or structuredClone rather than =.
  • Optional chaining (?.) reads a property safely when something along the path might be missing.

Check yourself

1. Given const user = { name: 'Asha' }, how do you read the name?
2. When do you need bracket notation?
3. What does user.age return if there is no age property?
4. What does Object.entries({ a: 1, b: 2 }) return?
5. const a = { n: 1 }; const b = a; b.n = 2; What is a.n?