Objects

JavaScript · Essentials · 12 min

Objects are JavaScript's fundamental data structure; nearly everything you work with is one.

An object is a collection of key–value pairs called properties:

const user = { name: "Ada", age: 36, "favorite color": "green" };

Read and write properties with dot notation (user.name) or bracket notation (user["favorite color"]). Brackets are required when the key isn't a valid identifier or is stored in a variable: user[field]. Reading a missing property gives undefined rather than an error.

Object literals have handy shorthands:

  • { name, age } means { name: name, age: age }.
  • Computed keys: { [key]: value }.
  • Methods: { greet() { return "Hi " + this.name; } }.

Add a property by assigning it, remove one with delete obj.key. Check whether a property exists with Object.hasOwn(obj, "key") (own properties only) or "key" in obj (includes inherited ones).

To iterate, convert to arrays: Object.keys(obj), Object.values(obj), Object.entries(obj), usually with for...of. Object.fromEntries(pairs) goes the other way. Keys are strings (or symbols); numeric-looking keys are converted to strings and listed first in ascending order, then other strings in insertion order.

Like arrays, objects are handled by reference: passing an object to a function lets the function modify the caller's object. Copy shallowly with { ...obj } or Object.assign({}, obj).

Plain objects are ideal for records with known fields. For dictionaries with arbitrary keys that you add and remove frequently, a Map (covered later) is often a better fit.

Example

const key = "role";
const name = "Ada";
const user = {
  name,                         // shorthand for name: name
  [key]: "admin",               // computed key
  "favorite color": "green",
  greet() { return `Hi, I'm ${this.name}`; },
};

console.log(user.greet());              // Hi, I'm Ada
console.log(user["favorite color"]);    // green
console.log(user.email);                // undefined

user.email = "ada@example.com";         // add
delete user["favorite color"];          // remove
console.log(Object.hasOwn(user, "email")); // true

for (const [k, v] of Object.entries(user)) {
  if (typeof v !== "function") console.log(k, "=", v);
}
// name = Ada, role = admin, email = ada@example.com

Remember

  • Dot notation for fixed names, brackets for dynamic or unusual keys
  • Shorthands: { name }, { [key]: v }, { method() {} }
  • Object.entries + for...of is the idiomatic way to iterate an object

Watch out for

  • Writing obj.key when the key is in a variable — that looks up the literal property "key".

Check yourself

  1. const field = "age"; const p = { age: 30 }; — which expression returns 30?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_objects