Objects

A collection of related values, stored as named properties.

What is it?

Arrays suit ordered lists, but a lot of data is a group of related details instead, like a person's name, age and email. An object stores values under named keys instead of numbered positions, so you can describe one thing with several properties in one place.

Explain like I'm 10

If an array is a row of numbered lockers, an object is a filing cabinet with labeled drawers (like "name" or "age"). You open a drawer by its label, not its position.

Examples

Creating and using an object

const user = {
  name: "Amara",
  age: 28,
  isAdmin: false,
};

console.log(user.name);      // "Amara"
console.log(user["age"]);    // 28

user.age = 29; // update a property

Read properties with dot notation (user.name) or bracket notation (user["age"]). Brackets are useful when the key is dynamic.

Objects with methods

const user = {
  name: "Amara",
  greet() {
    console.log("Hi, I'm " + this.name);
  },
};

user.greet(); // "Hi, I'm Amara"

A function stored as a property is a method. Inside it, this refers to the object it was called on.

How it works

An object stores each value under a key. user.name looks up the key "name" and returns its value. Unlike arrays, there's no numeric order: you access things by name, not position.

A variable holding an object actually holds a reference: directions to where the object lives. Copying the variable with = copies only the directions, so both variables point at the same object, and a change through one shows through the other.

Why does it exist?

Real things have several attributes at once: a product has a name, price and stock count; a user has an email and a role. Objects group that data together instead of spreading it across separate variables.

When to use it

Use an object to describe one thing with several named attributes: a user, a product, a settings config. If you'd ask "what properties does it have?" rather than "what position is it at?", it's an object.

When not to use it

If your data is a sequence of similar items, use an array (or an array of objects), not an object with numbered-looking keys. For very large collections you search by key constantly, a Map can fit better than a plain object.

Common mistakes

  • Trying to access a property that doesn't exist and being surprised it returns undefined instead of an error.

  • Confusing objects with arrays — using numeric indexes on an object won't work the way you expect.

  • Forgetting that copying an object with = copies a reference, not a brand-new independent object.

Practice exercises

  1. Easy:

    Create an object representing a book with title, author, and pages properties.

  2. Medium:

    Write a function that takes a user object and returns a greeting string using its name property.

  3. Hard:

    Write a function that takes an array of objects (e.g. products) and returns only the ones where inStock is true.

Interview questions

What is an object in JavaScript, and how is it different from an array?

A collection of values stored under named keys (properties) instead of numeric positions. You get a value by its key, not its place in a sequence, which suits a set of attributes rather than an ordered list.

When is bracket notation required instead of dot notation?

When the key is in a variable (user[key]), computed at runtime, or isn't a valid identifier. user["first-name"] can't be written user.first-name, which would parse as subtraction.

How do you check whether a key exists on an object?

"name" in user checks own and inherited keys; Object.hasOwn(user, "name") checks only own properties. user.name !== undefined is unreliable, since a key can exist with the value undefined.

What does this log? `const obj = {}; console.log("toString" in obj); console.log(Object.hasOwn(obj, "toString"));`

true then false. Every object inherits toString from Object.prototype, so in (which checks the prototype chain) finds it, but Object.hasOwn only checks properties on obj itself.

What do `Object.keys()`, `Object.values()`, and `Object.entries()` each return?

Object.keys(obj) returns the object's own enumerable property names; Object.values(obj) returns their values; Object.entries(obj) returns [key, value] pairs, which you loop over with for...of to get both.

What does this log? `const a = {}; const b = a; b.x = 1; console.log(a.x);`

1. Like arrays, objects are reference types: b = a copies the reference, so both point to the same object and a change through b shows through a.

Why does `{} === {}` evaluate to `false`?

=== compares references, not contents. Two object literals are two separate objects, so they're never ===, even with identical properties.

How do you make a shallow copy of an object?

Object spread ({ ...obj }) or Object.assign({}, obj). Both copy top-level properties into a new object, but nested objects and arrays are still shared with the original.

What does this log? `const original = { info: { age: 20 } }; const copy = { ...original }; copy.info.age = 21; console.log(original.info.age);`

21. Spread copies one level deep, so copy.info and original.info are the same nested object.

How would you actually deep-clone an object, and what are the trade-offs?

structuredClone(obj) handles most values natively, including dates, nested objects/arrays and cycles. JSON.parse(JSON.stringify(obj)) also deep-clones, but silently drops functions and undefined, turns dates into strings, and throws on circular references.

What determines what `this` refers to inside an object method?

How it's called, not where it's defined. obj.method() sets this to obj for that call. Called any other way (stored in a variable, passed as a callback), the same function gets a different this, or none.

What does this log? `const user = { name: "Amara", greet() { console.log(this.name); } }; const greet = user.greet; greet();`

undefined (or a TypeError in strict mode/modules). Storing user.greet in a plain variable detaches it from user, so when called as a plain function, this is no longer user.

What does this log, and why is it a common mistake? `const obj = { name: "Amara", greet: () => console.log(this.name) };` then calling `obj.greet()`

It logs undefined. Arrow functions have no own this; they take it from the scope where the object literal was written (usually module or global scope), never from the object.

What is a computed property name, and when do you need one?

{ [key]: value } uses an expression's value as a key in an object literal, instead of a fixed, typed-out name. Useful when the key comes from a variable or argument.

What is object shorthand syntax?

When a key and its value's variable have the same name, write { name } instead of { name: name }. Method shorthand lets you write greet() {} instead of greet: function () {}.

What does this log? `const user = {}; console.log(user.address?.city);`

undefined, without throwing. ?. stops at the first null/undefined link. user.address is undefined, so the whole expression is undefined instead of throwing on undefined.city.

What's the difference between `??` and `||` when supplying a default value?

|| falls back for any falsy value (0, "", false, null, undefined). ?? (nullish coalescing) falls back only for null or undefined, so valid falsy values like 0 or "" are kept.

What does `Object.freeze()` do, and what's a common misconception about it?

It stops adding, removing or reassigning an object's own top-level properties. The misconception is that it freezes deeply. It doesn't: nested objects stay fully mutable.

What does this log? `const obj = Object.freeze({ a: { b: 1 } }); obj.a.b = 2; console.log(obj.a.b);`

2. Object.freeze only locks the object it's called on. The nested object at obj.a was never frozen.

What's the difference between declaring an object with `const` and freezing it with `Object.freeze()`?

const only stops the variable from being reassigned; the object can still be changed. Object.freeze() stops the object's own properties from changing. They solve different problems and are often used together.

What's the difference between the `in` operator/`for...in` and `Object.keys()` for checking or iterating properties?

in and for...in walk the whole prototype chain, so they can include inherited properties. Object.keys() (and Object.entries()) return only the object's own enumerable properties, which is almost always what you want.

Why can't you call `.map()` or `.filter()` directly on a plain object?

They're array methods, and a plain object isn't an array. Convert with Object.entries(), run .map()/.filter() on the pairs, then rebuild with Object.fromEntries().

What does this log? `const a = { x: 1, y: 2 }; const b = { y: 3, z: 4 }; console.log({ ...a, ...b });`

{ x: 1, y: 3, z: 4 }. When spreading several objects, later keys overwrite earlier ones, so b's y wins.

What's the difference between `Object.assign(target, source)` and `{ ...source }`?

Object.assign copies source's properties into target, mutating and returning it. Spread always creates a new object and changes nothing. Passing {} as the target makes Object.assign non-mutating, like spread.

How do you rename a property while destructuring it out of an object?

const { name: userName } = user; takes the name property and stores it in a local variable userName. Useful to avoid name clashes or use a clearer name.

What does this log? `function updateAge(person) { person.age = 30; } const p = { age: 20 }; updateAge(p); console.log(p.age);`

30. person points to the same object as p, so changing a property through it is visible to the caller, just like with arrays.

If reassigning a function parameter to a new object doesn't affect the caller, but mutating it does, what's actually being copied when an object is passed to a function?

The reference, copied by value. The function gets its own copy of the pointer, not the object. Repointing that copy doesn't affect the caller; changing a property does, because both pointers lead to the same object.

Why does using `JSON.stringify()` to compare two objects for equality sometimes give a false negative?

JSON.stringify keeps key insertion order, so equal objects whose keys were added in a different order give different strings. It also can't represent undefined, functions or symbols consistently.

Why does a plain object literal like `{}` already have methods such as `toString()` that you never defined?

Plain objects inherit from Object.prototype (unless created with something like Object.create(null)), so methods like toString() and hasOwnProperty() are available without writing them.

What's a practical use for a `Symbol` as an object property key?

A Symbol key is unique and is skipped by Object.keys(), for...in and JSON.stringify(). That makes it handy for attaching metadata or "hidden" internal state without clashing with regular properties.

How would you loop over both the keys and values of an object at once?

for (const [key, value] of Object.entries(obj)) { ... }. Object.entries() gives [key, value] pairs, which for...of destructures on each pass.

What happens if you try to use an object as a property key on another plain object?

Plain object keys are strings (or symbols), so the object is converted to the string "[object Object]". Different objects used as keys silently collide on the same property. Use a Map when you need real objects as keys.

What happens if you destructure a property that doesn't exist on the object, and no default is given?

The variable is undefined, just like reading a missing property (obj.missing). It doesn't throw.

Can an object property's default value in destructuring reference another property being destructured in the same pattern?

Yes, if that property comes earlier in the pattern. Defaults run left to right, so const { a = 1, b = a } = {} gives b === 1. Referring to a later one (const { b = a, a = 1 } = {}) throws a ReferenceError, because a isn't initialized yet.