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.
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
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
<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:
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 12The [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:
<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 intotarget. 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 thaninwhen 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.keyinstead ofuser[key]. - Expecting
constto stop changes to the object. - Comparing objects with
===, which compares references, so{} === {}isfalse. - Reading deep paths without checking, like
user.address.citywhenaddressmay 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
<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.