Skip to the page

Objects, prototypes and classes · core

Objects, property access and key order

Objects are collections of string- or symbol-keyed properties; knowing how to create them, read them safely (?. and ??), check ownership (Object.hasOwn vs in) and copy them with spread covers most everyday object questions.

The notes

What you must know

  • Ways to create: object literal, Object.create(proto) (including Object.create(null) for a dictionary with no prototype), a constructor or class with new, a factory function.
  • Dot vs bracket access: brackets for dynamic keys and keys like 'data-id'. Keys are converted to strings (symbols excepted), so obj[1] and obj['1'] are the same, and obj[{}] uses the key '[object Object]'.
  • Key order: integer-like keys first in ascending order, then other string keys in insertion order, then symbols. Object.keys and JSON.stringify follow it.
  • 'k' in obj checks own and inherited properties; Object.hasOwn(obj, 'k') checks own properties only. obj.k !== undefined is wrong when the stored value is undefined.
  • Iteration: for...in visits own and inherited enumerable string keys (avoid); Object.keys/values/entries give own enumerable string keys; Reflect.ownKeys gives all own keys including symbols.
  • ?. stops and returns undefined at null or undefined. ?? falls back only for null or undefined, while || also replaces 0, '' and false.
  • Spread, rest and destructuring are shallow; later keys win; destructuring defaults apply only when the value is undefined.

The red pen

Common traps: mistake → fix

  • Mistake: Object keys always keep insertion order

    Fix: integer-like keys are sorted first.

  • Mistake: value || default is safe

    Fix: it replaces 0 and ''; use ??.

  • Mistake: 'k' in obj means obj owns k

    Fix: it includes inherited keys ('toString' in {} is true).

  • Mistake: Destructuring defaults apply for null

    Fix: only for undefined.

Easy to hard

Questions interviewers ask, easy to hard

  1. What are the ways to create an object?
  2. Dot vs bracket notation: what happens with obj[1] vs obj['1']?
  3. How do you check if an object has a property? Compare in, hasOwn and !== undefined.
  4. Predict the Object.keys order for mixed keys.
  5. When do you use ?? instead of ||? Why is Object.create(null) useful for dictionaries?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview