JavaScript Objects: Properties, Methods and Keys
An object groups related values under named properties: { name: "Noah", city: "Seattle" }. Where an array answers "what is at position 2?", an object answers "what is the city?". Objects are the building block of almost all JavaScript data, from settings to API responses.
Reading and writing properties
Dot notation, user.name, is the usual way. Bracket notation, user["favorite color"], is required when the key contains spaces or dashes, or when the key is in a variable, as in user[key]. Assigning to a property that does not exist creates it, and assigning to an existing one replaces its value. delete user.age removes a property.
Reading a missing property returns undefined instead of throwing. But reading a property of undefined does throw a TypeError. Optional chaining, user.email?.length, stops and returns undefined if the part before ?. is null or undefined.
Expected output
Noah teal
{name: "Noah", city: "Portland", age: 31}
true undefined undefined
Portland
["name", "city", "age"] 3
name: Noah
city: Portland
age: 31
(1, 2)Inspecting an object
"age" in userchecks whether a property exists.Object.keys(obj)returns the property names,Object.values(obj)the values, andObject.entries(obj)an array of[key, value]pairs.for (const [k, v] of Object.entries(user))loops over keys and values together, using array destructuring from the next chapter.
Properties keep insertion order for string keys, with one exception: keys that look like whole numbers come first, in numeric order.
Methods and this
A property whose value is a function is a method. The shorthand toString() { ... } defines one. Inside a method called as point.toString(), this refers to point. Template literals call toString() automatically, which is why ${point} prints (1, 2).
Objects are references
Assigning an object to another variable does not copy it; both names point at the same object. Copy with spread, { ...user }, which is covered in the next chapter.
Common mistakes
- Using dot notation with a variable:
user.keylooks for a property literally namedkey. - Reading deep properties without
?.and crashing onundefined. - Comparing objects with
===, which checks identity, not contents.
Summary
- Objects map property names to values; use dot or bracket notation.
- Missing properties are
undefined;?.guards deep reads. Object.keys,valuesandentrieslist an object's contents.- Functions stored in properties are methods, with
thisas the object.
Quiz: Objects