Interview Q&A · JavaScript · 12 questions in this topic
Objects & Prototypes — JavaScript Interview Q&A
Prototype-based objects — literals, property mechanics, inheritance chains and classes as sugar. Part of Objects, Prototypes & this · 204 questions in the JavaScript bank.
How do you create and use objects (literals, property access)?
Answer
Literals ({}) with shorthand ({x}), computed keys ({[k]: v}), and methods; access via dot (static known keys) or brackets (dynamic keys, special names). Destructuring unpacks; spread/rest clones and picks.
Brackets-for-dynamic, dot-for-static is the access rule.
Example
const k = 'role'; const u = { name: 'Al', [k]: 'admin' }; const { name } = u; // destructure const copy = { ...u, active: true }; // spread clone+extend
What is the prototype chain? How does property lookup work?
Answer
Every object links to a prototype (Object.getPrototypeOf); failed own-property lookups walk up the chain to Object.prototype, then undefined. Assignment always writes own properties (never up-chain); methods live on prototypes so instances share them.
Lookup-up, write-own is the two-direction rule.
Example
const animal = { speak() { return '...'; } }; const dog = Object.create(animal); // dog.__proto__ === animal dog.speak(); // found up-chain
💡 Shared-methods-on-prototype is the memory rationale.
How does prototypal inheritance differ from classical inheritance?
Answer
Prototypal: objects inherit directly from objects (live delegation links, mutable at runtime). Classical (Java-style): classes stamp instances from blueprints. JavaScript classes are sugar over constructor-prototype wiring — the chain underneath stays prototypal.
Delegation-links vs blueprints is the paradigm split.
Example
class Dog extends Animal { bark() {} } // sugar over: // Dog.prototype.__proto__ === Animal.prototype
💡 Sugar-over-prototypes explains why instanceof and extends still chain.
What are getters/setters and property descriptors?
Answer
Accessors (get/set) compute on access — validation, laziness, deprecation shims. Descriptors (writable, enumerable, configurable via defineProperty) control assignment, iteration and redefinition. Defaults from literals are all-true; defineProperty defaults all-false.
Computed-access plus fine-grained-flags is the property control story.
Example
const o = { _n: 1, get n() { return this._n; }, set n(v) { if (v > 0) this._n = v; }, };
How do you clone objects (shallow vs deep)?
Answer
Spread/Object.assign shallow-copies top level (nested shared). structuredClone deep-clones (handles cycles, Dates, Maps — not functions/DOM). JSON round-trip deep-clones JSON-safe data only (loses undefined, functions, Dates become strings).
Shallow default, structuredClone for true depth, JSON only for JSON-safe shapes.
Key points
- 1Spread — shallow, nested shared.
- 2structuredClone — true deep (no functions).
- 3JSON — deep, JSON-safe subset only.
Example
const deep = structuredClone({ a: { b: 1 }, d: new Date() });
What is the difference between `Object.keys`, `values`, `entries`, `getOwnPropertyNames`?
Answer
keys/values/entries cover string-keyed enumerable own properties (+entries pairs for iteration/destructuring). getOwnPropertyNames adds non-enumerables. getOwnPropertySymbols covers symbols. for...in walks the whole prototype chain (guard with hasOwn).
Enumerable-own-strings is the keys/values/entries scope; the others widen it.
Example
const o = { a: 1, b: 2 }; Object.entries(o); // [['a',1],['b',2]] for (const [k, v] of Object.entries(o)) {} // destructurable
What are classes (constructors, extends, super, statics)?
Answer
class declares constructor-prototype blueprints: constructor initializes, methods share via prototype, extends links parents (super calls parent ctor/methods — mandatory before this in derived ctors), statics attach to the class.
Sugar with rules: construction requires new, methods are non-enumerable, super-before-this.
Example
class Animal { constructor(name) { this.name = name; } speak() { return `${this.name}...`; } } class Dog extends Animal { constructor(n) { super(n); } }
What are private fields (#) and static blocks?
Answer
#fields are truly private (SyntaxError outside, no reflection escape) with static variants; static blocks run once at class definition for complex static init. Unlike _convention (public by honesty) and closures (per-instance methods), # gives class-level hard privacy.
Default # for internals; static blocks for computed statics.
Example
class C { #x = 1; static { /* one-time static setup */ } get() { return this.#x; } }
💡 Hard-privacy-at-class-level is the # proposition.
How does `instanceof` work (and when does it lie)?
Answer
instanceof walks the left object's prototype chain for the right's .prototype (customizable via Symbol.hasInstance). It lies across realms (iframes: Array from another frame fails) — Array.isArray and duck-typing survive realms.
Same-realm hierarchies: instanceof; cross-realm arrays: Array.isArray.
Example
[] instanceof Array; // true (same realm) Array.isArray([]); // true (realm-safe)
How do you implement inheritance without `class` (ES5 style)?
Answer
Constructor functions plus prototype wiring: Child.prototype = Object.create(Parent.prototype) (not new Parent — avoids running ctor), reset constructor property, call Parent.call(this) inside Child for instance state.
This is what class desugars to — knowing it proves the sugar understanding.
Example
function Parent(n) { this.n = n; } function Child(n, m) { Parent.call(this, n); this.m = m; } Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child;
💡 Object.create-not-new-Parent is the critical detail.
What is `Object.create(null)` (dictionary objects)?
Answer
Creates prototype-less objects — no inherited toString/hasOwnProperty, safe arbitrary keys ('constructor' won't collide). Ideal for lookup maps (with Map as the modern alternative offering size, iteration and key types).
Prototype-pollution-adjacent bugs (keys like __proto__) motivate both.
Example
const dict = Object.create(null); dict['constructor'] = 1; // safe: no prototype to collide with
How do `freeze`, `seal` and `preventExtensions` compare?
Answer
preventExtensions: no new properties (existing mutable). seal: plus no delete, existing writable (fixed shape). freeze: plus no writes (deep-immutable surface only — nested objects stay mutable).
Shape-stability (seal) aids optimization; freeze guards config/constants shallowly.
Key points
- 1preventExtensions — fixed key set.
- 2seal — plus fixed deletability.
- 3freeze — plus fixed values (shallow).
Example
const cfg = Object.freeze({ a: 1 }); // cfg.a = 2; // silent fail (sloppy) / throws (strict)
💡 Shallow-only is the freeze caveat to always add.
Recommended resourcesAffiliate links · may earn us a commission