[{"data":1,"prerenderedAt":534},["ShallowReactive",2],{"topic-javascript-objects":3},{"framework":4,"topic":15,"subtopics":24},{"id":5,"description":6,"extension":7,"icon":8,"meta":9,"name":10,"order":11,"slug":8,"stem":12,"tier":13,"__hash__":14},"frameworks\u002Fframeworks\u002Fjavascript.yml","Core JavaScript interview questions covering fundamentals, functions and closures, objects and prototypes, classes and OOP, and asynchronous programming with the event loop.","yml","javascript",{},"JavaScript",1,"frameworks\u002Fjavascript",0,"_TjxyYWBq7dftU9YakX_WX1Z4wAHq9uEUUW7wXL0y0c",{"id":16,"description":17,"extension":7,"frameworkSlug":8,"meta":18,"name":19,"order":20,"slug":21,"stem":22,"__hash__":23},"topics\u002Ftopics\u002Fjavascript-objects.yml","Object creation and properties, the prototype chain, prototypal inheritance and how the new operator builds objects — the heart of JavaScript's object model.",{},"Objects & Prototypes",4,"objects","topics\u002Fjavascript-objects","MljHH-t_2tN7XAsE57kKvNFYqNiVrpxWJD6_LiN-Ltk",[25,170,301,420],{"id":26,"title":27,"body":28,"description":32,"difficulty":35,"extension":36,"framework":10,"frameworkSlug":8,"meta":37,"navigation":38,"order":11,"path":39,"questions":40,"related":163,"seo":164,"seoDescription":165,"stem":166,"subtopic":167,"topic":19,"topicSlug":21,"updated":168,"__hash__":169},"qa\u002Fjavascript\u002Fobjects\u002Fobjects-properties.md","Objects Properties",{"type":29,"value":30,"toc":31},"minimark",[],{"title":32,"searchDepth":33,"depth":33,"links":34},"",2,[],"medium","md",{},true,"\u002Fjavascript\u002Fobjects\u002Fobjects-properties",[41,46,50,54,59,63,67,71,75,79,83,87,91,95,99,103,107,111,115,119,123,127,131,135,139,143,147,151,155,159],{"id":42,"difficulty":43,"q":44,"a":45},"create-object","easy","What are the ways to create an object in JavaScript?","Several, each with different use cases:\n\n```js\nconst a = {}                       \u002F\u002F object literal (most common)\nconst b = new Object()             \u002F\u002F constructor (rarely used)\nconst c = Object.create(proto)     \u002F\u002F with an explicit prototype\nfunction Point(x) { this.x = x }   \u002F\u002F constructor function\nconst d = new Point(1)\nclass P {}                         \u002F\u002F class\nconst e = new P()\n```\n\nThe **object literal** `{}` is by far the most common. `Object.create(proto)`\nis the only one that lets you set the prototype directly (or create a\nprototype-less object with `Object.create(null)`). Constructor functions and\nclasses are for producing many similar objects.\n",{"id":47,"difficulty":43,"q":48,"a":49},"access-properties","What is the difference between dot and bracket notation?","**Dot notation** (`obj.name`) is concise but only works for fixed, valid\nidentifier keys. **Bracket notation** (`obj['name']`) accepts any string or a\ncomputed expression — required for dynamic keys, keys with spaces\u002Fspecial\ncharacters, or numeric-like keys.\n\n```js\nobj.firstName          \u002F\u002F static key\nobj['first-name']      \u002F\u002F key with a hyphen — dot won't work\nconst key = 'age'\nobj[key]               \u002F\u002F dynamic key from a variable\n```\n\nUse dot notation by default; reach for brackets when the key is dynamic or not\na valid identifier.\n",{"id":51,"difficulty":43,"q":52,"a":53},"property-shorthand","What are shorthand properties and computed property names?","**Shorthand** lets you omit the value when a variable has the same name as the\nkey. **Computed names** let you use an expression as a key inside a literal.\n\n```js\nconst name = 'Ada', age = 36\nconst user = { name, age }              \u002F\u002F { name: 'Ada', age: 36 }\n\nconst field = 'email'\nconst obj = { [field]: 'a@b.com', [`is${field}`]: true }\n\u002F\u002F { email: 'a@b.com', isemail: true }\n\nconst methods = { greet() { return 'hi' } } \u002F\u002F method shorthand\n```\n\nThese ES6 features make object construction terser and enable dynamic keys\nwithout a separate assignment.\n",{"id":55,"difficulty":56,"q":57,"a":58},"property-descriptor","hard","What is a property descriptor?","Every property has a **descriptor** describing its attributes. Data properties\nhave `value`, `writable`, `enumerable`, and `configurable`; accessor properties\nhave `get`, `set`, `enumerable`, `configurable`.\n\n```js\nconst obj = {}\nObject.defineProperty(obj, 'id', {\n  value: 1,\n  writable: false,     \u002F\u002F can't reassign\n  enumerable: false,   \u002F\u002F hidden from for...in \u002F Object.keys\n  configurable: false, \u002F\u002F can't delete or redefine\n})\nObject.getOwnPropertyDescriptor(obj, 'id')\n```\n\nProperties created normally default all flags to `true`; `defineProperty`\ndefaults them to `false`. Descriptors let you create read-only or\nnon-enumerable properties — used heavily by the language internals.\n",{"id":60,"difficulty":35,"q":61,"a":62},"getters-setters","What are getters and setters?","Accessor properties that run a function on read (`get`) or write (`set`),\nletting a property be computed or validated while still being accessed like a\nnormal property.\n\n```js\nconst temp = {\n  celsius: 20,\n  get fahrenheit() { return this.celsius * 1.8 + 32 },\n  set fahrenheit(f) { this.celsius = (f - 32) \u002F 1.8 },\n}\ntemp.fahrenheit      \u002F\u002F 68 (computed)\ntemp.fahrenheit = 212\ntemp.celsius         \u002F\u002F 100\n```\n\nThey're useful for derived values, validation, and encapsulation. Define them\nwith `get`\u002F`set` syntax in a literal\u002Fclass, or via `Object.defineProperty`.\n",{"id":64,"difficulty":43,"q":65,"a":66},"object-keys-values-entries","What do Object.keys, Object.values and Object.entries return?","They return arrays of an object's **own enumerable** string-keyed properties:\n\n```js\nconst o = { a: 1, b: 2 }\nObject.keys(o)    \u002F\u002F ['a', 'b']\nObject.values(o)  \u002F\u002F [1, 2]\nObject.entries(o) \u002F\u002F [['a', 1], ['b', 2]]\n\nfor (const [k, v] of Object.entries(o)) console.log(k, v)\n```\n\nThey ignore inherited and non-enumerable properties (and symbol keys). They're\nthe standard way to iterate objects, and `Object.fromEntries` reverses\n`entries` back into an object.\n",{"id":68,"difficulty":35,"q":69,"a":70},"object-assign","What does Object.assign do?","`Object.assign(target, ...sources)` copies **own enumerable** properties from\nthe sources onto the target (a **shallow** copy) and returns the target.\n\n```js\nconst merged = Object.assign({}, defaults, overrides) \u002F\u002F merge into a new object\nconst clone = Object.assign({}, original)             \u002F\u002F shallow clone\n```\n\nIt only copies one level deep — nested objects are shared by reference. The\nspread operator `{ ...a, ...b }` does the same shallow merge more concisely and\nis usually preferred. `Object.assign` also triggers setters on the target.\n",{"id":72,"difficulty":43,"q":73,"a":74},"spread-objects","How does the object spread operator work?","`{ ...obj }` copies an object's own enumerable properties into a new object — a\nconcise shallow copy\u002Fmerge. Later spreads override earlier keys.\n\n```js\nconst updated = { ...user, name: 'Grace' } \u002F\u002F copy + override one field\nconst merged = { ...defaults, ...options }   \u002F\u002F options win on conflicts\n```\n\nLike `Object.assign`, it's **shallow** — nested objects are shared. It's the\nidiomatic way to do immutable updates (especially in React). Spread copies\nvalues, not getters (it evaluates them).\n",{"id":76,"difficulty":35,"q":77,"a":78},"delete-property","How do you remove a property from an object?","The `delete` operator removes a property entirely (so `'key' in obj` becomes\nfalse), returning `true` on success.\n\n```js\nconst obj = { a: 1, b: 2 }\ndelete obj.a\n'a' in obj  \u002F\u002F false\n```\n\nCaveats: `delete` only removes **own** properties (not inherited ones), can't\ndelete `configurable: false` properties, and can deoptimize objects in hot\npaths. For immutable removal, use destructuring: `const { a, ...rest } = obj`.\nSetting to `undefined` keeps the key; `delete` removes it.\n",{"id":80,"difficulty":35,"q":81,"a":82},"check-property-exists","How do you check if a property exists on an object?","Three common approaches, each subtly different:\n\n```js\n'key' in obj                       \u002F\u002F true for own AND inherited properties\nobj.hasOwnProperty('key')          \u002F\u002F own properties only\nObject.hasOwn(obj, 'key')          \u002F\u002F own only (modern, safer)\nobj.key !== undefined              \u002F\u002F fails if the value IS undefined\n```\n\nUse `in` when inherited properties count; use `Object.hasOwn` (ES2022) for own\nproperties — it's safer than `hasOwnProperty`, which can be shadowed or missing\non `Object.create(null)` objects. Checking `=== undefined` is unreliable.\n",{"id":84,"difficulty":56,"q":85,"a":86},"enumerable","What does \"enumerable\" mean for a property?","Enumerable properties show up in `for...in` loops, `Object.keys`, and spread;\nnon-enumerable ones are hidden from them (but still accessible directly).\n\n```js\nconst obj = { visible: 1 }\nObject.defineProperty(obj, 'hidden', { value: 2, enumerable: false })\nObject.keys(obj)             \u002F\u002F ['visible']\nobj.hidden                   \u002F\u002F 2 (still readable)\nObject.getOwnPropertyNames(obj) \u002F\u002F ['visible', 'hidden'] — includes non-enumerable\n```\n\nBuilt-in methods (like array methods on the prototype) are non-enumerable, so\nthey don't appear when you iterate. `getOwnPropertyNames` lists all own\nproperties regardless of enumerability.\n",{"id":88,"difficulty":35,"q":89,"a":90},"for-in","What does for...in iterate over, and what is its pitfall?","`for...in` iterates **enumerable string keys**, including **inherited** ones\nfrom the prototype chain — which is its main pitfall.\n\n```js\nfor (const key in obj) {\n  if (Object.hasOwn(obj, key)) {   \u002F\u002F guard against inherited keys\n    console.log(key, obj[key])\n  }\n}\n```\n\nAlways guard with `Object.hasOwn`\u002F`hasOwnProperty` unless you want inherited\nkeys. For arrays, prefer `for...of` (values) or a normal loop — `for...in`\niterates indices as strings and includes non-index enumerable properties.\n",{"id":92,"difficulty":35,"q":93,"a":94},"object-freeze","What is the difference between Object.freeze, seal and preventExtensions?","Three levels of locking down an object:\n\n- **`preventExtensions`** — can't add new properties; existing ones stay\n  writable\u002Fdeletable.\n- **`seal`** — preventExtensions + can't delete or reconfigure properties; values\n  still writable.\n- **`freeze`** — seal + can't change values. Fully immutable (shallowly).\n\n```js\nconst obj = Object.freeze({ a: 1, nested: { b: 2 } })\nobj.a = 9         \u002F\u002F ignored (throws in strict mode)\nobj.nested.b = 9  \u002F\u002F still works — freeze is SHALLOW\n```\n\nAll three are shallow. Check with `Object.isFrozen`\u002F`isSealed`. For deep\nimmutability, recursively freeze.\n",{"id":96,"difficulty":56,"q":97,"a":98},"shallow-vs-deep-clone","How do you deep clone an object?","Shallow copies (`{ ...obj }`, `Object.assign`) share nested references. For a\nfully independent copy, use **`structuredClone`** (modern, handles cycles,\nDates, Maps), or a library.\n\n```js\nconst deep = structuredClone(original)   \u002F\u002F best built-in option\n\nconst viaJson = JSON.parse(JSON.stringify(original)) \u002F\u002F loses functions,\n\u002F\u002F undefined, Symbols; breaks on Dates\u002FMaps\u002Fcycles\n```\n\n`structuredClone` is the standard now; the `JSON` trick works only for plain\nJSON-safe data and silently mangles everything else.\n",{"id":100,"difficulty":35,"q":101,"a":102},"object-references","Are objects compared by value or reference?","By **reference**. Two distinct objects with identical contents are not equal;\nonly two references to the *same* object are.\n\n```js\n{ a: 1 } === { a: 1 }   \u002F\u002F false (different objects)\nconst x = { a: 1 }\nconst y = x\nx === y                 \u002F\u002F true (same reference)\ny.a = 2; x.a            \u002F\u002F 2 — they share the object\n```\n\nAssigning an object copies the reference, not the object. This underlies\nshallow-copy bugs and why you need `structuredClone` for true independence.\n",{"id":104,"difficulty":43,"q":105,"a":106},"optional-chaining-objects","How does optional chaining help with nested objects?","`?.` short-circuits to `undefined` if a reference is `null`\u002F`undefined`, instead\nof throwing — safe access into deep structures.\n\n```js\nuser?.address?.city           \u002F\u002F undefined if user or address is missing\nuser?.getName?.()             \u002F\u002F call only if it exists\ndata?.items?.[0]              \u002F\u002F safe index access\nconst city = user?.address?.city ?? 'unknown'\n```\n\nIt stops evaluating at the first nullish link. Pair it with `??` for defaults.\nDon't overuse it to mask data that *should* exist — it can hide bugs.\n",{"id":108,"difficulty":35,"q":109,"a":110},"this-in-objects","What does this refer to in an object method?","In a regular-function method called as `obj.method()`, `this` is the object the\nmethod was called on. Extract the method, and `this` is lost.\n\n```js\nconst counter = {\n  count: 0,\n  inc() { this.count++ },\n}\ncounter.inc()              \u002F\u002F this === counter\nconst fn = counter.inc\nfn()                       \u002F\u002F this is undefined -> TypeError\n```\n\nUse method shorthand (a regular function) for methods that need `this`; avoid\narrow methods (their `this` is the outer scope, not the object).\n",{"id":112,"difficulty":56,"q":113,"a":114},"object-create-null","What is Object.create(null) used for?","It creates an object with **no prototype** — a \"pure dictionary\" with no\ninherited properties or methods (`toString`, `hasOwnProperty`, etc.).\n\n```js\nconst dict = Object.create(null)\ndict.key = 'value'\ndict.toString          \u002F\u002F undefined — no Object.prototype\n'toString' in dict     \u002F\u002F false\n```\n\nUseful as a safe map where user-controlled keys won't collide with inherited\nproperty names (e.g. a key literally named `\"hasOwnProperty\"`). The trade-off:\nobject methods aren't available, so use `Object.keys(dict)` etc. (A `Map` is\noften a cleaner choice.)\n",{"id":116,"difficulty":35,"q":117,"a":118},"object-vs-map","When should you use a Map instead of an object?","Use a **`Map`** when keys are dynamic or non-string, when you need ordering and\neasy size, or when you frequently add\u002Fremove entries.\n\n| | Object | Map |\n| --- | --- | --- |\n| Keys | strings\u002Fsymbols | **any type** |\n| Order | mostly insertion (quirky for integer keys) | guaranteed insertion |\n| Size | `Object.keys(o).length` | `map.size` |\n| Iteration | needs `Object.entries` | directly iterable |\n| Prototype keys | risk of collisions | none |\n\nUse a plain **object** for fixed, known-shape records and when you need JSON\nserialization (Maps don't `JSON.stringify` directly).\n",{"id":120,"difficulty":56,"q":121,"a":122},"getownpropertynames","How do you list all properties including non-enumerable and symbols?","`Object.keys` misses non-enumerable and symbol keys. Use the fuller reflection\nmethods:\n\n```js\nObject.getOwnPropertyNames(obj)    \u002F\u002F all string keys (incl. non-enumerable)\nObject.getOwnPropertySymbols(obj)  \u002F\u002F symbol keys\nReflect.ownKeys(obj)               \u002F\u002F EVERYTHING: strings + symbols\n```\n\n`Reflect.ownKeys` is the complete list of own keys. These are needed for deep\ncloning, serialization, and metaprogramming where you must see every property.\n",{"id":124,"difficulty":56,"q":125,"a":126},"property-order","In what order are object keys iterated?","Modern engines follow a spec order: **integer-like keys first, in ascending\nnumeric order**, then **string keys in insertion order**, then **symbol keys in\ninsertion order**.\n\n```js\nconst obj = { b: 1, 2: 1, a: 1, 1: 1 }\nObject.keys(obj) \u002F\u002F ['1', '2', 'b', 'a'] — numbers sorted, then strings as added\n```\n\nSo integer-like keys are *not* in insertion order — a surprise if you rely on\norder. If you need strict insertion order for all keys, use a **`Map`**.\n",{"id":128,"difficulty":43,"q":129,"a":130},"method-vs-property","What is the difference between a method and a property?","A **property** holds a value; a **method** is a property whose value is a\nfunction, so it can be called.\n\n```js\nconst obj = {\n  name: 'Ada',           \u002F\u002F property\n  greet() { return 'hi' }, \u002F\u002F method (function-valued property)\n}\nobj.name      \u002F\u002F 'Ada'\nobj.greet()  \u002F\u002F 'hi'\n```\n\nMethods are just properties that happen to be functions — `typeof obj.greet`\nis `'function'`. Defining a method with shorthand also makes it non-arrow, so\n`this` works correctly.\n",{"id":132,"difficulty":35,"q":133,"a":134},"tostring-override","How do you control how an object converts to a string or number?","Override `toString`\u002F`valueOf`, or implement `Symbol.toPrimitive` for full\ncontrol over coercion.\n\n```js\nconst money = {\n  amount: 100,\n  [Symbol.toPrimitive](hint) {\n    return hint === 'string' ? `$${this.amount}` : this.amount\n  },\n  toString() { return `$${this.amount}` },\n}\n`${money}`   \u002F\u002F '$100'\nmoney + 1    \u002F\u002F 101\n```\n\nWithout these, objects coerce to `[object Object]` (string) via `toString`.\n`Symbol.toPrimitive` takes precedence and receives a hint (`'string'`,\n`'number'`, `'default'`).\n",{"id":136,"difficulty":35,"q":137,"a":138},"json-stringify-object","How does JSON.stringify handle objects?","It serializes **own enumerable** properties, but silently drops `undefined`,\nfunctions, and symbols, converts `NaN`\u002F`Infinity` to `null`, and calls a\n`toJSON()` method if present.\n\n```js\nJSON.stringify({ a: 1, b: undefined, c: () => {}, d: Symbol() })\n\u002F\u002F '{\"a\":1}'  — b, c, d dropped\n\nJSON.stringify(obj, ['a', 'b'])        \u002F\u002F replacer array: only these keys\nJSON.stringify(obj, null, 2)           \u002F\u002F pretty-print with 2-space indent\n```\n\n`BigInt` and circular references **throw**. The optional replacer and space\narguments control filtering and formatting.\n",{"id":140,"difficulty":35,"q":141,"a":142},"chaining-optional-assignment","What does the logical assignment operator ||= and ??= do with objects?","They assign only when the left side is falsy (`||=`) or nullish (`??=`) — handy\nfor defaulting object properties.\n\n```js\nconst config = { timeout: 0 }\nconfig.timeout ||= 1000   \u002F\u002F 1000 overwrites valid 0\nconfig.timeout ??= 1000   \u002F\u002F 0    only fills null\u002Fundefined\nconfig.retries ??= 3      \u002F\u002F adds retries: 3\n```\n\n`??=` is the safe choice when `0`\u002F`''`\u002F`false` are valid values. They're\nshorthand for `x = x ?? value` and short-circuit (the right side isn't\nevaluated if no assignment happens).\n",{"id":144,"difficulty":35,"q":145,"a":146},"object-is","How do you compare two objects for equality?","`===` only checks reference identity, so you must compare contents yourself for\n\"same data\" equality.\n\n```js\nconst shallowEqual = (a, b) => {\n  const ak = Object.keys(a), bk = Object.keys(b)\n  return ak.length === bk.length && ak.every((k) => a[k] === b[k])\n}\n```\n\nFor nested structures you need a recursive **deep equality** (lodash `isEqual`).\nThe `JSON.stringify(a) === JSON.stringify(b)` trick works only for simple data\nand is sensitive to key order and `undefined`.\n",{"id":148,"difficulty":56,"q":149,"a":150},"defineproperties","What is the difference between defining a property and assigning it?","Plain assignment (`obj.x = 1`) creates an enumerable, writable, configurable\ndata property — or **triggers an inherited setter** if one exists.\n`Object.defineProperty` creates the property with explicit (default `false`)\nflags and **bypasses** setters.\n\n```js\nobj.x = 1   \u002F\u002F enumerable: true, writable: true, configurable: true\nObject.defineProperty(obj, 'y', { value: 2 })\n\u002F\u002F enumerable: false, writable: false, configurable: false\n```\n\nUse assignment for normal data; use `defineProperty` for read-only, hidden, or\naccessor properties, or to define multiple at once with `defineProperties`.\n",{"id":152,"difficulty":43,"q":153,"a":154},"nullish-vs-or-default","How do you set default values when destructuring an object?","Provide defaults in the destructuring pattern; they apply only when the value\nis `undefined` (not `null` or other falsy values).\n\n```js\nconst { timeout = 1000, retries = 3, mode = 'auto' } = options\nconst { a: alias = 5 } = obj            \u002F\u002F rename + default\nfunction f({ x = 0, y = 0 } = {}) {}     \u002F\u002F default for the whole object too\n```\n\nThe `= {}` default on the parameter prevents a crash when the argument is\nomitted entirely. Defaults trigger only on `undefined`, so an explicit `null`\noverrides them.\n",{"id":156,"difficulty":35,"q":157,"a":158},"copy-with-rest","How do you copy an object while omitting some properties?","Use destructuring with a **rest** pattern — the named keys are excluded, the\nrest collected into a new object.\n\n```js\nconst { password, ...safe } = user   \u002F\u002F `safe` has everything except password\nconst { [dynamicKey]: _, ...rest } = obj \u002F\u002F omit a dynamic key\n```\n\nThis is the idiomatic immutable \"remove a property\" — it produces a new object\nwithout mutating the original (unlike `delete`). Great for stripping sensitive\nfields before sending data.\n",{"id":160,"difficulty":35,"q":161,"a":162},"object-grouping","How do you transform or group object data?","Convert to entries, transform, and convert back with `Object.fromEntries`:\n\n```js\n\u002F\u002F double every value\nconst doubled = Object.fromEntries(\n  Object.entries(obj).map(([k, v]) => [k, v * 2])\n)\n\u002F\u002F filter keys\nconst filtered = Object.fromEntries(\n  Object.entries(obj).filter(([, v]) => v > 10)\n)\n```\n\n`Object.entries` + array methods + `Object.fromEntries` is the functional\npattern for mapping\u002Ffiltering objects (which have no native `map`\u002F`filter`).\n`Object.groupBy` (ES2024) groups an array into an object by a key function.\n",null,{"description":32},"JavaScript object interview questions — creating objects, property descriptors, getters and setters, Object methods, enumeration, freezing and copying.","javascript\u002Fobjects\u002Fobjects-properties","Objects & Properties","2026-06-18","8e9eu-hN4JNeXrO12JjJ3sUR5YmuDgSldUUI50UInGc",{"id":171,"title":172,"body":173,"description":32,"difficulty":56,"extension":36,"framework":10,"frameworkSlug":8,"meta":177,"navigation":38,"order":33,"path":178,"questions":179,"related":163,"seo":296,"seoDescription":297,"stem":298,"subtopic":299,"topic":19,"topicSlug":21,"updated":168,"__hash__":300},"qa\u002Fjavascript\u002Fobjects\u002Fprototypes-chain.md","Prototypes Chain",{"type":29,"value":174,"toc":175},[],{"title":32,"searchDepth":33,"depth":33,"links":176},[],{},"\u002Fjavascript\u002Fobjects\u002Fprototypes-chain",[180,184,188,192,196,200,204,208,212,216,220,224,228,232,236,240,244,248,252,256,260,264,268,272,276,280,284,288,292],{"id":181,"difficulty":35,"q":182,"a":183},"what-is-prototype","What is a prototype in JavaScript?","Every object has an internal link to another object called its **prototype**.\nWhen you access a property that the object doesn't have, JavaScript looks it up\non the prototype, then that object's prototype, and so on — the **prototype\nchain**. This is how objects inherit behavior in JavaScript.\n\n```js\nconst arr = [1, 2, 3]\narr.map(x => x)  \u002F\u002F `map` isn't on `arr`; it's found on Array.prototype\n```\n\nPrototypes are how methods are **shared** across many instances without copying\nthem onto each object — the foundation of JavaScript's object model.\n",{"id":185,"difficulty":56,"q":186,"a":187},"proto-vs-prototype","What is the difference between __proto__ and prototype?","They're related but distinct:\n\n- **`prototype`** is a property of **constructor functions** (and classes). It's\n  the object that becomes the prototype of instances created with `new`.\n- **`__proto__`** (or `Object.getPrototypeOf`) is the actual **prototype link**\n  on every object — pointing to the object it inherits from.\n\n```js\nfunction Dog() {}\nconst d = new Dog()\nd.__proto__ === Dog.prototype          \u002F\u002F true\nObject.getPrototypeOf(d) === Dog.prototype \u002F\u002F true (preferred check)\n```\n\nSo `Constructor.prototype` is what *instances* get as their `__proto__`. Use\n`Object.getPrototypeOf`\u002F`setPrototypeOf` instead of the legacy `__proto__`.\n",{"id":189,"difficulty":35,"q":190,"a":191},"prototype-chain-lookup","How does property lookup work along the prototype chain?","When you read `obj.prop`, the engine checks `obj` first; if not found, it\nfollows `obj`'s prototype, then that object's prototype, until it finds the\nproperty or reaches `null` (returning `undefined`).\n\n```js\nconst animal = { eats: true }\nconst dog = Object.create(animal)\ndog.barks = true\ndog.barks   \u002F\u002F true (own)\ndog.eats    \u002F\u002F true (inherited from animal)\ndog.flies   \u002F\u002F undefined (not found anywhere)\n```\n\nWriting a property, by contrast, always creates\u002Fupdates an **own** property on\nthe object itself — it doesn't modify the prototype (unless an inherited setter\nintercepts it).\n",{"id":193,"difficulty":35,"q":194,"a":195},"end-of-chain","What is at the end of the prototype chain?","The chain ends at **`null`**. Most objects inherit from `Object.prototype`,\nwhose prototype is `null`.\n\n```js\nconst obj = {}\nObject.getPrototypeOf(obj) === Object.prototype       \u002F\u002F true\nObject.getPrototypeOf(Object.prototype) === null      \u002F\u002F true\n```\n\n`Object.prototype` provides `toString`, `hasOwnProperty`, `valueOf`, etc., which\nis why nearly every object has them. An object made with `Object.create(null)`\nhas **no** prototype, so its chain is empty.\n",{"id":197,"difficulty":35,"q":198,"a":199},"methods-on-prototype","Why are methods defined on the prototype instead of each instance?","Putting methods on the prototype means **one shared copy** for all instances,\ninstead of a separate function per object — saving memory and allowing methods\nto be updated in one place.\n\n```js\nfunction User(name) { this.name = name }\nUser.prototype.greet = function () { return `Hi, ${this.name}` }\n\nconst a = new User('Ada'), b = new User('Bob')\na.greet === b.greet   \u002F\u002F true — shared method\n```\n\nEach instance holds only its own data (`name`); the behavior lives once on\n`User.prototype`. Classes do this automatically (methods go on the prototype).\n",{"id":201,"difficulty":35,"q":202,"a":203},"hasownproperty","How do you tell own properties from inherited ones?","Use `hasOwnProperty` \u002F `Object.hasOwn`, which check **only own** properties,\nunlike `in` which also sees inherited ones.\n\n```js\nconst dog = Object.create({ eats: true })\ndog.barks = true\n'eats' in dog              \u002F\u002F true (inherited)\nObject.hasOwn(dog, 'eats') \u002F\u002F false (not own)\nObject.hasOwn(dog, 'barks')\u002F\u002F true\n```\n\n`Object.hasOwn` (ES2022) is the modern, robust form — it works even on\n`Object.create(null)` objects and can't be shadowed by an own property named\n`hasOwnProperty`.\n",{"id":205,"difficulty":43,"q":206,"a":207},"getprototypeof","How do you get and set an object's prototype?","Use `Object.getPrototypeOf` to read and `Object.setPrototypeOf` (or\n`Object.create`) to set — prefer these over the legacy `__proto__`.\n\n```js\nconst proto = { greet() { return 'hi' } }\nconst obj = Object.create(proto)        \u002F\u002F create WITH a prototype\nObject.getPrototypeOf(obj) === proto     \u002F\u002F true\nObject.setPrototypeOf(obj, otherProto)   \u002F\u002F change it (slow — avoid in hot code)\n```\n\n`Object.setPrototypeOf` deoptimizes the object and is slow; set the prototype at\ncreation time with `Object.create` or a constructor\u002Fclass instead.\n",{"id":209,"difficulty":35,"q":210,"a":211},"prototype-inheritance-vs-class","How do classes relate to prototypes?","`class` is **syntactic sugar** over prototypes. Class methods are put on the\nconstructor's `prototype`, and `extends` sets up the prototype chain — the same\nmechanism, nicer syntax.\n\n```js\nclass User {\n  constructor(name) { this.name = name }\n  greet() { return `Hi, ${this.name}` }   \u002F\u002F -> User.prototype.greet\n}\ntypeof User              \u002F\u002F 'function'\nUser.prototype.greet     \u002F\u002F the method lives here\n```\n\nUnder the hood there are no \"real\" classes — `class` desugars to constructor\nfunctions + prototype assignment, with some extras (strict mode, non-enumerable\nmethods, `new`-only invocation).\n",{"id":213,"difficulty":35,"q":214,"a":215},"shadowing","What is property shadowing in the prototype chain?","An **own** property with the same name as an inherited one **shadows** (hides)\nthe prototype's version — lookup stops at the own property.\n\n```js\nconst proto = { greet: () => 'from proto' }\nconst obj = Object.create(proto)\nobj.greet = () => 'from obj'\nobj.greet()  \u002F\u002F 'from obj' — shadows the prototype's greet\ndelete obj.greet\nobj.greet()  \u002F\u002F 'from proto' — inherited version reappears\n```\n\nAssigning to an inherited property creates an own one (shadowing); it doesn't\nchange the prototype. Deleting the own property reveals the inherited one again.\n",{"id":217,"difficulty":35,"q":218,"a":219},"instanceof-prototype","How does instanceof use the prototype chain?","`obj instanceof Ctor` checks whether `Ctor.prototype` appears **anywhere** in\n`obj`'s prototype chain.\n\n```js\nclass Animal {}\nclass Dog extends Animal {}\nconst d = new Dog()\nd instanceof Dog     \u002F\u002F true\nd instanceof Animal  \u002F\u002F true (Animal.prototype is in the chain)\nd instanceof Object  \u002F\u002F true\n```\n\nSo it tests prototype-chain membership, not the exact constructor. It can break\nacross realms (iframes) and if you reassign `prototype`; `Symbol.hasInstance`\ncan customize its behavior.\n",{"id":221,"difficulty":56,"q":222,"a":223},"constructor-property","What is the constructor property on the prototype?","Every function's `prototype` object has a `constructor` property pointing back\nto the function. Instances inherit it, so you can find the constructor that made\nan object.\n\n```js\nfunction User() {}\nUser.prototype.constructor === User   \u002F\u002F true\nconst u = new User()\nu.constructor === User                 \u002F\u002F true (inherited)\n```\n\nGotcha: if you **replace** `Prototype` entirely (`User.prototype = {...}`), you\nlose the `constructor` link unless you set it back. It's mostly informational\nand shouldn't be relied on for type checks.\n",{"id":225,"difficulty":56,"q":226,"a":227},"extend-builtin","Can you add methods to built-in prototypes, and should you?","You technically can (`Array.prototype.last = function(){...}`), but you\n**shouldn't** — modifying built-in prototypes (monkey-patching) risks clashing\nwith future language features or other libraries, and breaks `for...in`.\n\n```js\n\u002F\u002F avoid — pollutes every array, may collide with a future Array.prototype\nArray.prototype.last = function () { return this[this.length - 1] }\n```\n\nPrefer standalone utility functions or subclasses. The one time it's acceptable\nis a carefully scoped **polyfill** that implements a standardized method on old\nengines.\n",{"id":229,"difficulty":56,"q":230,"a":231},"prototype-pollution","What is prototype pollution?","A security vulnerability where untrusted input modifies `Object.prototype`,\naffecting **every** object in the program — often via unsafe deep-merge or\nproperty assignment using a `__proto__` key.\n\n```js\n\u002F\u002F attacker payload: { \"__proto__\": { \"isAdmin\": true } }\nmerge({}, JSON.parse(userInput))\n;({}).isAdmin   \u002F\u002F true — every object now \"has\" isAdmin\n```\n\nMitigate by rejecting `__proto__`\u002F`constructor`\u002F`prototype` keys, using\n`Object.create(null)` or `Map` for user data, and `Object.freeze(Object.\nprototype)`. It's a real-world exploit in many libraries.\n",{"id":233,"difficulty":43,"q":234,"a":235},"array-prototype-methods","Where do array and string methods come from?","They live on the built-in prototypes — `Array.prototype`, `String.prototype`,\netc. — and are inherited by every array\u002Fstring via the prototype chain.\n\n```js\n[1, 2].map          === Array.prototype.map     \u002F\u002F true\n'hi'.toUpperCase    === String.prototype.toUpperCase \u002F\u002F true\n```\n\nThat's why all arrays share the same `map`\u002F`filter`. Primitives like strings are\ntemporarily **boxed** into wrapper objects so they can reach their prototype\nmethods, then discarded.\n",{"id":237,"difficulty":56,"q":238,"a":239},"borrow-methods","How do you borrow methods from a prototype?","Use `call`\u002F`apply` to invoke a prototype method with a different `this` — handy\nfor array-like objects that lack array methods.\n\n```js\nfunction sum() {\n  return Array.prototype.reduce.call(arguments, (a, b) => a + b, 0)\n}\nArray.prototype.slice.call(document.querySelectorAll('div')) \u002F\u002F NodeList -> array\n```\n\nMethod borrowing leverages that prototype methods are just functions decoupled\nfrom their objects via `this`. Modern code often uses `Array.from`\u002Fspread\ninstead, but borrowing shows how the chain and `this` interact.\n",{"id":241,"difficulty":35,"q":242,"a":243},"own-vs-inherited-enumeration","Do Object.keys and for...in include inherited properties?","- **`Object.keys`** — own enumerable properties only.\n- **`for...in`** — own **and inherited** enumerable properties.\n\n```js\nconst proto = { inherited: 1 }\nconst obj = Object.create(proto)\nobj.own = 2\nObject.keys(obj)            \u002F\u002F ['own']\nfor (const k in obj) console.log(k)  \u002F\u002F 'own', then 'inherited'\n```\n\nThis is why `for...in` needs a `hasOwn` guard. Built-in prototype methods are\nnon-enumerable, so they don't show up in `for...in` — only your own additions\nto prototypes would.\n",{"id":245,"difficulty":35,"q":246,"a":247},"create-vs-new","What is the difference between Object.create and new?","- **`Object.create(proto)`** sets the new object's prototype to `proto` and runs\n  **no constructor**.\n- **`new Fn()`** creates an object whose prototype is `Fn.prototype`, then runs\n  `Fn` as a constructor (initializing the object).\n\n```js\nconst a = Object.create(protoObj)   \u002F\u002F prototype = protoObj, no init\nconst b = new Ctor(args)            \u002F\u002F prototype = Ctor.prototype, runs Ctor\n```\n\n`Object.create` is lower-level (just sets up the link); `new` is the full\nconstructor flow. `new Ctor()` is roughly `Object.create(Ctor.prototype)` plus\ncalling `Ctor` with the new object as `this`.\n",{"id":249,"difficulty":56,"q":250,"a":251},"differential-inheritance","What is \"differential inheritance\" \u002F delegation?","JavaScript's prototype model is **delegation-based**: objects don't copy\nproperties from a \"class,\" they **delegate** missing property lookups to their\nprototype at runtime. Each object stores only what differs from its prototype.\n\n```js\nconst base = { type: 'shape', area() { return 0 } }\nconst circle = Object.create(base)\ncircle.r = 2\ncircle.area = function () { return Math.PI * this.r ** 2 } \u002F\u002F override only this\n```\n\nChanges to the prototype are immediately visible to all delegating objects (a\nlive link), unlike class-based copying. This is why the model is sometimes\ncalled \"objects linking to other objects\" (OLOO).\n",{"id":253,"difficulty":35,"q":254,"a":255},"prototype-method-update","What happens if you change a prototype after instances exist?","Because the prototype link is **live**, existing instances immediately see\nchanges to their prototype.\n\n```js\nfunction User() {}\nconst u = new User()\nUser.prototype.greet = function () { return 'hi' }\nu.greet()   \u002F\u002F 'hi' — added after u was created, but visible\n```\n\nThis is a consequence of delegation: instances don't copy the prototype, they\nreference it. (Reassigning the whole `prototype` object, however, only affects\n*future* instances — existing ones keep their old prototype.)\n",{"id":257,"difficulty":35,"q":258,"a":259},"typeof-vs-instanceof","When do you use typeof vs instanceof?","- **`typeof`** — for **primitives** and detecting functions (`'string'`,\n  `'number'`, `'function'`, …).\n- **`instanceof`** — for checking whether an object is built by a particular\n  constructor\u002Fclass (prototype-chain membership).\n\n```js\ntypeof 'hi'           \u002F\u002F 'string'\ntypeof []             \u002F\u002F 'object' (useless for arrays)\n[] instanceof Array   \u002F\u002F true\nnew Date instanceof Date \u002F\u002F true\n```\n\n`typeof null` is `'object'` and `typeof []` is `'object'`, so use\n`Array.isArray` for arrays and `instanceof`\u002Fduck-typing for object kinds.\n",{"id":261,"difficulty":56,"q":262,"a":263},"function-prototype","Do arrow functions have a prototype property?","No. Arrow functions **lack a `prototype`** property and can't be used with\n`new`, because they're not designed to be constructors.\n\n```js\nconst arrow = () => {}\narrow.prototype          \u002F\u002F undefined\nnew arrow()              \u002F\u002F TypeError: arrow is not a constructor\n\nfunction regular() {}\nregular.prototype        \u002F\u002F {} — usable as a constructor\n```\n\nOnly regular functions (and classes) have a `prototype` object for building\ninstances. This is one of several reasons arrows are lightweight callbacks, not\ngeneral-purpose functions.\n",{"id":265,"difficulty":56,"q":266,"a":267},"chain-performance","Does a long prototype chain affect performance?","Slightly — each missing-property lookup walks the chain until found or `null`,\nso very deep chains add overhead. In practice engines optimize this heavily\n(inline caches), so it rarely matters for normal depths.\n\n```js\n\u002F\u002F accessing a deeply inherited property walks more links\ndeep.someInheritedMethod()  \u002F\u002F traverses several prototypes\n```\n\nBigger wins come from not reassigning prototypes at runtime\n(`setPrototypeOf` deoptimizes) and keeping object \"shapes\" stable. Don't\nmicro-optimize chain depth; do avoid dynamic prototype mutation in hot paths.\n",{"id":269,"difficulty":56,"q":270,"a":271},"mixin-prototype","How do you mix methods from multiple sources into a prototype?","Since JavaScript has single-prototype inheritance, you compose extra behavior by\n**copying methods** onto a prototype — a mixin.\n\n```js\nconst serializable = { toJSON() { return { ...this } } }\nconst loggable = { log() { console.log(this) } }\n\nclass Model {}\nObject.assign(Model.prototype, serializable, loggable)\nnew Model().log()\n```\n\n`Object.assign(Class.prototype, ...mixins)` adds shared methods without a\nsuperclass — the standard way to share behavior across unrelated classes.\n",{"id":273,"difficulty":35,"q":274,"a":275},"null-prototype-pitfall","What breaks when an object has no prototype?","`Object.create(null)` objects lack `Object.prototype`, so the usual methods\n(`toString`, `hasOwnProperty`, `valueOf`) are missing.\n\n```js\nconst dict = Object.create(null)\ndict.toString()              \u002F\u002F TypeError: not a function\n`${dict}`                    \u002F\u002F throws — can't coerce to string\nObject.keys(dict)            \u002F\u002F static methods still work\ndict.hasOwnProperty          \u002F\u002F undefined -> use Object.hasOwn(dict, k)\n```\n\nUse the **static** `Object.*` methods instead of instance methods. The benefit\n(no inherited keys to collide with) is why they're used as safe maps — but a\n`Map` usually avoids these pitfalls entirely.\n",{"id":277,"difficulty":56,"q":278,"a":279},"setprototypeof-vs-create","Why is Object.setPrototypeOf discouraged?","Changing an existing object's prototype forces engines to **deoptimize** it\n(its hidden class\u002Fshape changes), which is slow and can hurt every later access\nto that object.\n\n```js\n\u002F\u002F slow — mutates an existing object's prototype\nconst obj = {}\nObject.setPrototypeOf(obj, proto)\n\n\u002F\u002F fast — set the prototype at creation\nconst obj2 = Object.create(proto)\n```\n\nSet the prototype **once at creation** (`Object.create`, a class, or a\nconstructor) rather than mutating it later. MDN explicitly warns about\n`setPrototypeOf`'s performance impact.\n",{"id":281,"difficulty":35,"q":282,"a":283},"prototype-vs-composition","Is prototypal inheritance better than composition?","Neither is universally better — they solve different problems. Prototypal\ninheritance shares behavior down an is-a chain; **composition** builds behavior\nby combining small, independent pieces (often favored for flexibility).\n\n```js\n\u002F\u002F composition: assemble capabilities\nconst canFly = (s) => ({ fly: () => `${s.name} flies` })\nconst bird = (name) => { const s = { name }; return { ...s, ...canFly(s) } }\n```\n\nDeep inheritance chains get rigid; composition (mixins, factory functions,\ndelegation) tends to scale better. The common guidance \"favor composition over\ninheritance\" applies in JS too.\n",{"id":285,"difficulty":56,"q":286,"a":287},"getter-on-prototype","Can getters and setters live on a prototype?","Yes — accessor properties defined on a prototype are inherited and run with the\ninstance as `this`, so derived values work per instance.\n\n```js\nclass Circle {\n  constructor(r) { this.r = r }\n  get area() { return Math.PI * this.r ** 2 }  \u002F\u002F on Circle.prototype\n}\nnew Circle(2).area   \u002F\u002F 12.56... — `this` is the instance\n```\n\nClass getters\u002Fsetters live on the prototype (shared definition), but execute\nagainst each instance. You can also add them via\n`Object.defineProperty(proto, 'x', { get, set })`.\n",{"id":289,"difficulty":56,"q":290,"a":291},"realm-instanceof","Why can instanceof fail across iframes or realms?","Each realm (iframe, worker, Node vm) has its **own** built-in constructors and\nprototypes. An array from another frame has a different `Array.prototype`, so\n`arr instanceof Array` is `false` in your realm.\n\n```js\nconst iframeArray = iframe.contentWindow.eval('[1, 2]')\niframeArray instanceof Array   \u002F\u002F false — different Array constructor\nArray.isArray(iframeArray)     \u002F\u002F true — realm-agnostic\n```\n\nPrefer realm-safe checks: `Array.isArray`, `Object.prototype.toString.call(x)`\n(`'[object Array]'`), or duck typing — not `instanceof` — for cross-realm code.\n",{"id":293,"difficulty":56,"q":294,"a":295},"oloo","What is the OLOO pattern?","\"Objects Linking to Other Objects\" — a style (popularized by Kyle Simpson) that\nuses `Object.create` and delegation directly, without constructors, `new`, or\nclasses, embracing JavaScript's prototypal nature.\n\n```js\nconst Widget = {\n  init(w) { this.width = w; return this },\n  render() { return `width: ${this.width}` },\n}\nconst button = Object.create(Widget).init(100)\nbutton.render()  \u002F\u002F 'width: 100'\n```\n\nIt avoids the `new`\u002F`this`\u002F`prototype` ceremony and makes the delegation\nexplicit. It's a minority style — classes are more common — but it clarifies how\nprototypes actually work.\n",{"description":32},"JavaScript prototype interview questions — the prototype chain, __proto__ vs prototype, property lookup, inheritance, and how methods are shared.","javascript\u002Fobjects\u002Fprototypes-chain","Prototypes & the Prototype Chain","apN3WJNktEDjBw2n8sZQhdM5ksCiMFRiWPSCKdSPYa8",{"id":302,"title":303,"body":304,"description":32,"difficulty":56,"extension":36,"framework":10,"frameworkSlug":8,"meta":308,"navigation":38,"order":309,"path":310,"questions":311,"related":163,"seo":416,"seoDescription":417,"stem":418,"subtopic":303,"topic":19,"topicSlug":21,"updated":168,"__hash__":419},"qa\u002Fjavascript\u002Fobjects\u002Fprototypal-inheritance.md","Prototypal Inheritance",{"type":29,"value":305,"toc":306},[],{"title":32,"searchDepth":33,"depth":33,"links":307},[],{},3,"\u002Fjavascript\u002Fobjects\u002Fprototypal-inheritance",[312,316,320,324,328,332,336,340,344,348,352,356,360,364,368,372,376,380,384,388,392,396,400,404,408,412],{"id":313,"difficulty":35,"q":314,"a":315},"what-is-prototypal-inheritance","What is prototypal inheritance?","A model where objects inherit directly from **other objects** (their prototype),\nrather than from classes. A missing property is looked up on the prototype\nchain, so one object can reuse another's properties and methods.\n\n```js\nconst animal = { eats: true, walk() { return 'walking' } }\nconst rabbit = Object.create(animal)\nrabbit.jumps = true\nrabbit.walk()  \u002F\u002F 'walking' — inherited\nrabbit.eats    \u002F\u002F true — inherited\n```\n\nJavaScript's inheritance is fundamentally object-to-object **delegation**. Even\n`class` is sugar over this prototypal mechanism.\n",{"id":317,"difficulty":35,"q":318,"a":319},"object-create-inheritance","How do you implement inheritance with Object.create?","`Object.create(proto)` makes a new object whose prototype is `proto`, giving you\ndirect prototypal inheritance with no constructors.\n\n```js\nconst base = {\n  init(name) { this.name = name; return this },\n  describe() { return `I am ${this.name}` },\n}\nconst child = Object.create(base)\nchild.shout = function () { return this.describe().toUpperCase() }\n\nconst c = Object.create(child).init('Ada')\nc.shout()  \u002F\u002F 'I AM ADA'\n```\n\nEach level delegates to the one above. This is the most direct expression of\nprototypal inheritance — no `new`, no `prototype` juggling.\n",{"id":321,"difficulty":56,"q":322,"a":323},"constructor-inheritance","How do you set up inheritance between constructor functions?","Call the parent constructor for the instance fields, and link the prototypes so\nmethods are inherited.\n\n```js\nfunction Animal(name) { this.name = name }\nAnimal.prototype.eat = function () { return `${this.name} eats` }\n\nfunction Dog(name) {\n  Animal.call(this, name)               \u002F\u002F inherit instance properties\n}\nDog.prototype = Object.create(Animal.prototype) \u002F\u002F inherit methods\nDog.prototype.constructor = Dog                 \u002F\u002F restore constructor\nDog.prototype.bark = function () { return 'woof' }\n```\n\nThis is the pre-ES6 pattern: `Parent.call(this)` for fields,\n`Object.create(Parent.prototype)` for the method chain, and reset\n`constructor`. `class extends` does all this for you.\n",{"id":325,"difficulty":35,"q":326,"a":327},"class-vs-prototypal","What is the difference between classical and prototypal inheritance?","- **Classical** (Java\u002FC++): classes are blueprints; objects are **instances**\n  that copy structure from the class hierarchy.\n- **Prototypal** (JavaScript): objects **delegate** to live prototype objects;\n  there's no copying, and the link is dynamic.\n\n```js\n\u002F\u002F prototypal: changing the prototype affects existing objects live\nconst proto = { greet() { return 'hi' } }\nconst obj = Object.create(proto)\nproto.greet = () => 'hello'\nobj.greet()  \u002F\u002F 'hello' — live delegation, not a copy\n```\n\nJavaScript's `class` *looks* classical but is prototypal underneath. The key\ndifference is delegation (live links) vs copying (static blueprints).\n",{"id":329,"difficulty":56,"q":330,"a":331},"super-in-prototypal","How do you call a parent method from a child (without class)?","Reference the parent prototype's method and invoke it with the right `this` via\n`call`.\n\n```js\nDog.prototype.eat = function () {\n  const base = Animal.prototype.eat.call(this)  \u002F\u002F call parent, keep `this`\n  return base + ' noisily'\n}\n```\n\nWith `class`, `super.method()` does this cleanly. Without classes, you must\nexplicitly grab `Parent.prototype.method` and `call` it with the instance, or\nthe parent method would run with the wrong `this`.\n",{"id":333,"difficulty":43,"q":334,"a":335},"override-method","How does method overriding work with prototypes?","Define a method with the same name lower in the chain (on the child); it shadows\nthe parent's version because lookup stops at the first match.\n\n```js\nconst animal = { speak() { return '...' } }\nconst dog = Object.create(animal)\ndog.speak = function () { return 'Woof' }  \u002F\u002F overrides\ndog.speak()                                 \u002F\u002F 'Woof'\nObject.getPrototypeOf(dog).speak()          \u002F\u002F '...' (parent still reachable)\n```\n\nThe override is just a closer own\u002Fprototype property. The parent method remains\naccessible via the prototype if you need to call it (the manual `super`).\n",{"id":337,"difficulty":35,"q":338,"a":339},"factory-functions","What are factory functions and how do they relate to inheritance?","A factory function returns a new object without `new` or classes — often using\nclosures for state and composition (rather than prototype chains) for behavior.\n\n```js\nfunction createUser(name) {\n  return {\n    name,\n    greet() { return `Hi, ${name}` },\n  }\n}\nconst u = createUser('Ada')\n```\n\nFactories favor **composition over inheritance**: instead of inheriting from a\nprototype, you assemble objects from pieces. Trade-off: methods aren't shared on\na prototype (each object gets its own), costing some memory for many instances.\n",{"id":341,"difficulty":35,"q":342,"a":343},"mixins","What are mixins?","A way to share behavior across unrelated objects\u002Fclasses by **copying methods**\nin, instead of inheriting — JavaScript's answer to the lack of multiple\ninheritance.\n\n```js\nconst serializable = { serialize() { return JSON.stringify(this) } }\nconst comparable = { equals(o) { return this.id === o.id } }\n\nclass Model {}\nObject.assign(Model.prototype, serializable, comparable)\n```\n\nMixins let a class gain capabilities from several sources. They're a flexible\nalternative to deep inheritance — compose the behaviors a type needs rather than\nforcing a single hierarchy.\n",{"id":345,"difficulty":56,"q":346,"a":347},"diamond-problem","Does JavaScript have the diamond problem?","Not in the classic multiple-inheritance sense, because each object has a\n**single** prototype chain — there's no ambiguity over which parent a method\ncomes from. But **mixins** can reintroduce conflicts when two mixins define the\nsame method.\n\n```js\nconst a = { run() { return 'a' } }\nconst b = { run() { return 'b' } }\nObject.assign(target, a, b)\ntarget.run()  \u002F\u002F 'b' — last one wins, silently\n```\n\nWith `Object.assign`, the last source wins on key collisions (no error). So\nsingle-prototype inheritance avoids diamonds, but you must manage mixin method\nclashes yourself.\n",{"id":349,"difficulty":35,"q":350,"a":351},"prototype-vs-instance-property","Should shared state go on the prototype?","No — only **methods** (and true constants) belong on the prototype. Mutable\nshared state on a prototype is accidentally shared by all instances.\n\n```js\nfunction Cart() {}\nCart.prototype.items = []        \u002F\u002F ALL carts share one array\nconst a = new Cart(), b = new Cart()\na.items.push('x')\nb.items                          \u002F\u002F ['x'] — leaked!\n\nfunction Cart2() { this.items = [] }  \u002F\u002F per-instance state in the constructor\n```\n\nPut per-instance data on `this` in the constructor; put shared behavior on the\nprototype. (This mirrors the Java \"mutable static field\" trap.)\n",{"id":353,"difficulty":56,"q":354,"a":355},"inherit-static","Are static-like properties inherited?","Constructor functions have their **own** prototype chain\n(`Child.__proto__ === Parent` when using `class extends`), so \"static\"\nproperties on the parent constructor are inherited by the child constructor.\n\n```js\nclass Parent { static create() { return new this() } }\nclass Child extends Parent {}\nChild.create()   \u002F\u002F works — static method inherited; `this` is Child\n```\n\n`extends` links both chains: instance methods via `Child.prototype ->\nParent.prototype`, and statics via `Child -> Parent`. With plain constructor\nfunctions you'd wire statics up manually.\n",{"id":357,"difficulty":56,"q":358,"a":359},"object-create-second-arg","What is the second argument to Object.create?","A **property descriptors** object — it lets you define own properties (with\nwritable\u002Fenumerable\u002Fconfigurable flags) at the same time as setting the\nprototype.\n\n```js\nconst obj = Object.create(proto, {\n  id: { value: 1, enumerable: true },\n  secret: { value: 42, enumerable: false },\n})\n```\n\nIt's the same descriptor format as `Object.defineProperties`. Rarely needed, but\nit's how you create an object with both a chosen prototype and precisely\nconfigured own properties in one call.\n",{"id":361,"difficulty":56,"q":362,"a":363},"parasitic-inheritance","What is parasitic \u002F functional inheritance?","An older pattern where a factory creates a base object, then **augments** it with\nextra properties\u002Fmethods before returning it — inheritance without prototypes.\n\n```js\nfunction createAnimal(name) {\n  const obj = { name }\n  obj.eat = () => `${name} eats`\n  return obj\n}\nfunction createDog(name) {\n  const dog = createAnimal(name)   \u002F\u002F \"inherit\" by starting from a base\n  dog.bark = () => 'woof'          \u002F\u002F augment\n  return dog\n}\n```\n\nIt uses composition\u002Fclosures instead of the prototype chain. Methods aren't\nshared (memory cost), but it's simple and avoids `this`\u002F`new` pitfalls.\n",{"id":365,"difficulty":35,"q":366,"a":367},"hasownproperty-inheritance","Why can iterating an inheriting object surprise you?","`for...in` walks inherited enumerable properties too, so an object that inherits\nfrom another can expose more keys than you expect.\n\n```js\nconst proto = { shared: 1 }\nconst obj = Object.create(proto)\nobj.own = 2\nfor (const k in obj) console.log(k)   \u002F\u002F 'own' AND 'shared'\n```\n\nGuard with `Object.hasOwn(obj, k)`, or iterate `Object.keys(obj)` (own only).\nThis is why adding enumerable properties to built-in prototypes is dangerous —\nit pollutes every `for...in`.\n",{"id":369,"difficulty":56,"q":370,"a":371},"super-property-vs-method","How does inheritance interact with getters and setters?","Inherited accessors run with the instance as `this`, so a child can override a\ngetter\u002Fsetter while the parent's still computes against the child's data.\n\n```js\nconst base = {\n  get label() { return `[${this.name}]` },\n}\nconst item = Object.create(base)\nitem.name = 'box'\nitem.label   \u002F\u002F '[box]' — inherited getter, `this` is item\n```\n\nOverriding an inherited setter and writing to the property creates an own data\nproperty unless the child also defines an accessor — a subtle source of bugs\nwhen mixing data and accessor properties across a chain.\n",{"id":373,"difficulty":35,"q":374,"a":375},"composition-over-inheritance-js","Why is composition often preferred over inheritance in JavaScript?","Deep inheritance chains are rigid: a change in a base ripples to all\ndescendants, and an object is locked into one hierarchy. **Composition** builds\nobjects from small, swappable behaviors, which is more flexible.\n\n```js\nconst withTimestamp = (o) => ({ ...o, createdAt: Date.now() })\nconst withId = (o) => ({ ...o, id: crypto.randomUUID() })\nconst record = withId(withTimestamp({ name: 'Ada' }))\n```\n\nCompose capabilities (functions, mixins, delegation) instead of inheriting them.\nThis avoids the fragile-base-class problem and the \"gorilla holding the banana\nand the entire jungle\" inheritance trap.\n",{"id":377,"difficulty":35,"q":378,"a":379},"instanceof-inheritance","How do you check an object's type through an inheritance chain?","`instanceof` returns true for any constructor whose `prototype` is in the chain,\nso it sees inherited types.\n\n```js\nclass Shape {}\nclass Circle extends Shape {}\nconst c = new Circle()\nc instanceof Circle   \u002F\u002F true\nc instanceof Shape    \u002F\u002F true (ancestor)\n```\n\nFor prototypal (non-class) inheritance, use\n`proto.isPrototypeOf(obj)` to ask \"is this object in obj's chain?\" — the\ndelegation-style equivalent of `instanceof`.\n",{"id":381,"difficulty":35,"q":382,"a":383},"isprototypeof","What does isPrototypeOf do?","`proto.isPrototypeOf(obj)` returns true if `proto` appears anywhere in `obj`'s\nprototype chain — the object-oriented complement to `instanceof` (which works\nwith constructors).\n\n```js\nconst animal = {}\nconst dog = Object.create(animal)\nanimal.isPrototypeOf(dog)            \u002F\u002F true\nObject.prototype.isPrototypeOf(dog)  \u002F\u002F true\n```\n\nIt's the natural type check for prototypal inheritance built with\n`Object.create`, where there's no constructor to use with `instanceof`.\n",{"id":385,"difficulty":35,"q":386,"a":387},"shared-method-this","How does this behave in an inherited method?","An inherited method is called on the instance, so `this` is the **instance**,\nnot the prototype where the method is defined.\n\n```js\nconst proto = { whoAmI() { return this.name } }\nconst a = Object.create(proto); a.name = 'A'\nconst b = Object.create(proto); b.name = 'B'\na.whoAmI()  \u002F\u002F 'A'\nb.whoAmI()  \u002F\u002F 'B' — same method, different `this`\n```\n\nThis is what makes shared prototype methods useful: one definition operates on\nwhichever instance invokes it. Lose the receiver (extract the method) and `this`\nbreaks, as always.\n",{"id":389,"difficulty":35,"q":390,"a":391},"multiple-levels","Can you have multiple levels of prototypal inheritance?","Yes — chains can be arbitrarily deep, each level delegating to the next.\n\n```js\nconst a = { x: 1 }\nconst b = Object.create(a); b.y = 2\nconst c = Object.create(b); c.z = 3\nc.x  \u002F\u002F 1 (from a, two levels up)\nc.y  \u002F\u002F 2 (from b)\nc.z  \u002F\u002F 3 (own)\n```\n\nLookup walks `c -> b -> a -> Object.prototype -> null`. Deep chains work but get\nharder to reason about and slightly slower to traverse; flatter structures (or\ncomposition) are usually clearer.\n",{"id":393,"difficulty":56,"q":394,"a":395},"new-target","What is new.target and how does it help with inheritance?","`new.target` is the constructor that was invoked with `new` (or `undefined` for\na normal call). It lets a base constructor know which subclass is being built and\nenforce `new`.\n\n```js\nfunction Base() {\n  if (!new.target) throw new Error('Use new')\n  console.log(new.target.name)   \u002F\u002F logs the actual subclass\n}\nclass Sub extends Base {}\nnew Sub()   \u002F\u002F logs 'Sub'\n```\n\nUseful for abstract base classes (throw if `new.target === Base`) and for\nfactory logic that depends on the concrete type being constructed.\n",{"id":397,"difficulty":35,"q":398,"a":399},"prototype-chain-json","Does JSON.stringify include inherited properties?","No — `JSON.stringify` serializes **own enumerable** properties only, ignoring\nanything inherited from the prototype.\n\n```js\nconst proto = { inherited: 1 }\nconst obj = Object.create(proto)\nobj.own = 2\nJSON.stringify(obj)   \u002F\u002F '{\"own\":2}' — inherited is omitted\n```\n\nSo data on a prototype won't be serialized. If you need inherited values in\nJSON, copy them onto the object first (`{ ...proto, ...obj }`) or implement\n`toJSON`.\n",{"id":401,"difficulty":35,"q":402,"a":403},"when-classes-vs-prototypes","Should you use classes or raw prototypes today?","For most code, **use `class`** — it's clearer, standard, and handles the\nprototype wiring (`extends`\u002F`super`\u002Fstatics) correctly. Reach for raw\nprototypes\u002F`Object.create` only for low-level work, OLOO-style delegation, or\nunderstanding internals.\n\n```js\n\u002F\u002F idiomatic modern inheritance\nclass Animal { constructor(n) { this.name = n } speak() {} }\nclass Dog extends Animal { speak() { return 'Woof' } }\n```\n\nClasses and prototypes are the same machinery; classes just give you a safer,\nmore readable interface. Knowing prototypes still matters for debugging and edge\ncases.\n",{"id":405,"difficulty":35,"q":406,"a":407},"augmenting-instances","What is the cost of adding methods to instances vs the prototype?","Methods added to each **instance** are duplicated per object (more memory);\nmethods on the **prototype** are shared (one copy).\n\n```js\n\u002F\u002F a new function per instance\nfunction User(name) {\n  this.name = name\n  this.greet = function () { return this.name }\n}\n\u002F\u002F shared once\nUser.prototype.greet = function () { return this.name }\n```\n\nFor a handful of objects it doesn't matter; for thousands, prototype methods\nsave significant memory. Factory functions trade this away for closure-based\nprivacy — a deliberate choice.\n",{"id":409,"difficulty":35,"q":410,"a":411},"delegation-events","How does delegation in prototypes relate to event delegation?","Both are \"delegation\" but different ideas. **Prototypal delegation** forwards\n*property lookups* up the prototype chain. **Event delegation** attaches one\nlistener to a parent that handles events from many children via bubbling.\n\n```js\n\u002F\u002F event delegation (unrelated to prototypes)\nlist.addEventListener('click', (e) => {\n  if (e.target.matches('li')) handle(e.target)\n})\n```\n\nThey share a name and a \"let something else handle it\" spirit, but operate in\ncompletely different parts of the language\u002FDOM — a common point of confusion.\n",{"id":413,"difficulty":56,"q":414,"a":415},"clone-with-prototype","How do you clone an object while preserving its prototype?","Spread\u002F`Object.assign` copy own properties but give the clone a **plain object\nprototype**, losing the original's prototype. Preserve it explicitly:\n\n```js\nconst clone = Object.assign(\n  Object.create(Object.getPrototypeOf(original)),\n  original,\n)\n\u002F\u002F or structuredClone — but it does NOT preserve custom prototypes either\n```\n\n`{ ...obj }` and `structuredClone` both drop the custom prototype (the clone\nbecomes a plain object). To keep behavior, create the clone with\n`Object.create(getPrototypeOf(original))` then copy the own properties.\n",{"description":32},"JavaScript prototypal inheritance interview questions — Object.create, delegation, constructor inheritance, classical vs prototypal, and sharing behavior between objects.","javascript\u002Fobjects\u002Fprototypal-inheritance","GvqUS3PImrZ3Q2MJBGdT3949HLkhsnt0F70ivtrPQog",{"id":421,"title":422,"body":423,"description":32,"difficulty":35,"extension":36,"framework":10,"frameworkSlug":8,"meta":427,"navigation":38,"order":20,"path":428,"questions":429,"related":163,"seo":529,"seoDescription":530,"stem":531,"subtopic":532,"topic":19,"topicSlug":21,"updated":168,"__hash__":533},"qa\u002Fjavascript\u002Fobjects\u002Fnew-constructors.md","New Constructors",{"type":29,"value":424,"toc":425},[],{"title":32,"searchDepth":33,"depth":33,"links":426},[],{},"\u002Fjavascript\u002Fobjects\u002Fnew-constructors",[430,434,438,442,446,449,453,457,461,465,469,473,477,481,485,489,493,497,501,505,509,513,517,521,525],{"id":431,"difficulty":35,"q":432,"a":433},"what-does-new-do","What does the new operator do?","`new Fn(args)` performs four steps:\n\n1. Creates a fresh empty object.\n2. Sets that object's prototype to `Fn.prototype`.\n3. Calls `Fn` with `this` bound to the new object.\n4. Returns the new object — unless `Fn` explicitly returns its own object.\n\n```js\nfunction User(name) { this.name = name }\nconst u = new User('Ada')\n\u002F\u002F roughly:\n\u002F\u002F const u = Object.create(User.prototype)\n\u002F\u002F User.call(u, 'Ada')\n```\n\nThose four steps are the whole \"magic\" of `new`. Understanding them explains\n`this`, the prototype link, and the return-value rules below.\n",{"id":435,"difficulty":43,"q":436,"a":437},"constructor-function","What is a constructor function?","A regular function intended to be called with `new` to create objects. By\nconvention its name is **capitalized**. Inside, `this` is the new instance.\n\n```js\nfunction Point(x, y) {\n  this.x = x\n  this.y = y\n}\nconst p = new Point(1, 2)   \u002F\u002F { x: 1, y: 2 }\n```\n\nThere's nothing special about the function itself — any function can be a\nconstructor. The capitalization is a signal to callers that it must be invoked\nwith `new`. Classes are the modern replacement.\n",{"id":439,"difficulty":56,"q":440,"a":441},"forget-new","What happens if you forget new on a constructor function?","Without `new`, the function runs as a plain call: `this` is `undefined` (strict)\nor the global object (sloppy), so it doesn't create an instance — and in sloppy\nmode it leaks properties onto the global object.\n\n```js\nfunction User(name) { this.name = name }\nconst u = User('Ada')   \u002F\u002F no new\nu                       \u002F\u002F undefined (function returns nothing)\n\u002F\u002F sloppy mode: created a global `name`!\n```\n\nGuards: use a `class` (which throws if called without `new`), or check\n`new.target`\u002F`instanceof` and re-invoke with `new`. This bug is exactly why\nclasses enforce `new`.\n",{"id":443,"difficulty":56,"q":444,"a":445},"return-from-constructor","What happens when a constructor returns a value?","If a constructor returns an **object**, that object replaces the newly created\n`this`. If it returns a **primitive** (or nothing), the primitive is ignored and\n`this` is returned as usual.\n\n```js\nfunction A() { this.x = 1; return { y: 2 } }\nnew A()   \u002F\u002F { y: 2 } — object return overrides `this`\n\nfunction B() { this.x = 1; return 42 }\nnew B()   \u002F\u002F { x: 1 } — primitive return ignored\n```\n\nThis \"return an object to override\" behavior enables some factory tricks but is\nusually a footgun — most constructors return nothing.\n",{"id":393,"difficulty":56,"q":447,"a":448},"What is new.target?","A meta-property that is the constructor invoked with `new`, or `undefined` for a\nnormal call. It lets a function detect how it was called.\n\n```js\nfunction User(name) {\n  if (!new.target) throw new Error('User must be called with new')\n  this.name = name\n}\nUser('Ada')      \u002F\u002F throws\nnew User('Ada')  \u002F\u002F\n```\n\nIn a class hierarchy, `new.target` is the actual subclass being constructed —\nuseful for abstract base classes and for factory logic that varies by concrete\ntype.\n",{"id":450,"difficulty":35,"q":451,"a":452},"new-and-prototype","How does new connect an instance to its prototype?","`new Fn()` sets the instance's prototype to `Fn.prototype`, so the instance\ninherits everything defined there.\n\n```js\nfunction Dog() {}\nDog.prototype.bark = () => 'woof'\nconst d = new Dog()\nObject.getPrototypeOf(d) === Dog.prototype  \u002F\u002F true\nd.bark()                                      \u002F\u002F 'woof' (inherited)\n```\n\nThat's why methods go on `Fn.prototype` — every `new` instance shares them via\nthe prototype link. Reassigning `Fn.prototype` after creating an instance\ndoesn't change that instance's prototype.\n",{"id":454,"difficulty":35,"q":455,"a":456},"constructor-vs-factory","What is the difference between a constructor and a factory function?","- A **constructor** is used with `new`, relies on `this`, and links instances to\n  a shared prototype.\n- A **factory** is a normal function that **returns** an object (no `new`, no\n  `this`), often using closures for privacy and composition for behavior.\n\n```js\nfunction User(name) { this.name = name }       \u002F\u002F constructor -> new User()\nfunction createUser(name) { return { name } }   \u002F\u002F factory -> createUser()\n```\n\nFactories avoid `new`\u002F`this` pitfalls and offer closure-based privacy;\nconstructors\u002Fclasses share methods via the prototype (more memory-efficient for\nmany instances). Both are valid.\n",{"id":458,"difficulty":35,"q":459,"a":460},"this-in-constructor","What is this inside a constructor?","When called with `new`, `this` is the brand-new instance being created, so\nassignments to `this.x` become the object's own properties.\n\n```js\nfunction Account(balance) {\n  this.balance = balance       \u002F\u002F own property of the new instance\n  this.deposit = function (n) { this.balance += n }\n}\n```\n\nCalled **without** `new`, `this` follows normal rules (undefined\u002Fglobal), which\nis the source of the \"forgot new\" bug. Inside a class constructor, `this` is the\ninstance (and is `undefined` until `super()` runs in a subclass).\n",{"id":462,"difficulty":35,"q":463,"a":464},"constructor-property-instance","How do you find which constructor created an object?","Use `instance.constructor` (inherited from the prototype) or `instanceof`.\n\n```js\nfunction User() {}\nconst u = new User()\nu.constructor === User        \u002F\u002F true\nu.constructor.name            \u002F\u002F 'User'\nu instanceof User             \u002F\u002F true\n```\n\n`constructor` is informational and can be wrong if the prototype was replaced\nwithout restoring it. For reliable type checks, prefer `instanceof` (or\nduck-typing), not the `constructor` property.\n",{"id":466,"difficulty":43,"q":467,"a":468},"built-in-constructors","What are the built-in constructors?","JavaScript provides constructors for its core types: `Object`, `Array`,\n`Function`, `Date`, `RegExp`, `Map`, `Set`, `Promise`, `Error`, and the wrapper\nconstructors `String`\u002F`Number`\u002F`Boolean`.\n\n```js\nnew Date()\nnew Map()\nnew Error('boom')\nnew Array(3)        \u002F\u002F [ \u003C3 empty items> ] — quirky\n```\n\nMost are used with `new`, though some (like `Array`, `Object`) also work without\nit. **Avoid** `new String\u002FNumber\u002FBoolean` — they create wrapper *objects* that\nbreak `===` and are always truthy.\n",{"id":470,"difficulty":35,"q":471,"a":472},"array-constructor-pitfall","What is the pitfall of the Array constructor?","`new Array(n)` with a **single number** creates an empty array of length `n`\n(holes), not an array containing `n`. With multiple args it creates an array of\nthose elements.\n\n```js\nnew Array(3)        \u002F\u002F [ \u003C3 empty items> ] — length 3, no values\nnew Array(1, 2, 3)  \u002F\u002F [1, 2, 3]\nArray.of(3)         \u002F\u002F [3] — the unambiguous alternative\nArray.from({length: 3}, (_, i) => i)  \u002F\u002F [0, 1, 2]\n```\n\nThis inconsistency is why `Array.of` exists and why array literals `[]` are\npreferred. The \"empty items\" are holes, which behave oddly with iteration.\n",{"id":474,"difficulty":35,"q":475,"a":476},"instanceof-check","How does instanceof relate to constructors?","`obj instanceof Ctor` is true when `Ctor.prototype` is in `obj`'s prototype\nchain — i.e. `obj` was (effectively) built by `Ctor` or a subclass.\n\n```js\nconst d = new Date()\nd instanceof Date    \u002F\u002F true\nd instanceof Object  \u002F\u002F true (Object.prototype is in the chain)\n```\n\nIt checks the prototype chain, not the literal constructor used, so it sees\ninheritance. It can be fooled by reassigned prototypes and fails across realms —\nuse `Array.isArray` \u002F `Object.prototype.toString` for those cases.\n",{"id":478,"difficulty":56,"q":479,"a":480},"super-in-constructor","Why must super() be called before this in a subclass constructor?","In a derived class, the instance (`this`) is created by the **parent**\nconstructor, so you must call `super()` first to initialize it. Accessing `this`\nbefore `super()` throws a `ReferenceError`.\n\n```js\nclass Animal { constructor(name) { this.name = name } }\nclass Dog extends Animal {\n  constructor(name) {\n    this.bark = true     \u002F\u002F ReferenceError — before super()\n    super(name)\n    this.bark = true     \u002F\u002F\n  }\n}\n```\n\nThis is a real difference from constructor functions, where `this` exists\nimmediately. The rule guarantees the parent has set up the object before the\nchild touches it.\n",{"id":482,"difficulty":56,"q":483,"a":484},"singleton-constructor","How can a constructor enforce a singleton?","Cache the instance and return it on subsequent `new` calls — leveraging the\n\"return an object overrides this\" rule.\n\n```js\nclass Config {\n  constructor() {\n    if (Config.instance) return Config.instance\n    Config.instance = this\n  }\n}\nnew Config() === new Config()   \u002F\u002F true — same instance\n```\n\nBecause returning an object from a constructor replaces the new `this`, the\nsecond `new` gets the cached instance. (A module-level singleton or a frozen\nobject is often simpler.)\n",{"id":486,"difficulty":35,"q":487,"a":488},"prototype-methods-vs-constructor","Should methods go in the constructor or on the prototype?","Put **methods on the prototype** (shared, one copy); put **per-instance data**\nin the constructor (on `this`).\n\n```js\nfunction User(name) {\n  this.name = name                    \u002F\u002F instance data\n}\nUser.prototype.greet = function () {   \u002F\u002F shared method\n  return `Hi, ${this.name}`\n}\n```\n\nDefining methods inside the constructor (`this.greet = function(){}`) creates a\nnew function per instance — wasteful. Classes handle this correctly by placing\nmethods on the prototype automatically.\n",{"id":490,"difficulty":56,"q":491,"a":492},"new-with-bind","What happens when you use new on a bound function?","`new` **overrides** a bound `this` — the instance wins. Bound *arguments* are\nstill applied.\n\n```js\nfunction Point(x, y) { this.x = x; this.y = y }\nconst Bound = Point.bind({ ignored: true }, 10)  \u002F\u002F pre-bind x = 10\nconst p = new Bound(20)\np.x  \u002F\u002F 10 (bound arg kept)\np.y  \u002F\u002F 20\n\u002F\u002F the bound `this` ({ ignored: true }) is ignored — p is a fresh Point\n```\n\nThis reflects precedence: `new` beats explicit binding. It's the one case where\n`bind`'s \"permanent\" `this` doesn't hold.\n",{"id":494,"difficulty":35,"q":495,"a":496},"class-not-hoisted","Can you use a constructor before it is defined?","**Function** constructors are hoisted (usable before their line); **class**\nconstructors are hoisted but in the temporal dead zone, so they're **not** usable\nearly.\n\n```js\nnew Fn()              \u002F\u002F works — function declaration hoisted\nfunction Fn() {}\n\nnew Cls()             \u002F\u002F ReferenceError — TDZ\nclass Cls {}\n```\n\nSo switching from a constructor function to a class can break code that\ninstantiated it above its declaration. Always declare classes before use.\n",{"id":498,"difficulty":56,"q":499,"a":500},"abstract-base","How do you make an abstract base constructor that can't be instantiated?","Check `new.target` against the base and throw, so only subclasses can be\ncreated.\n\n```js\nclass Shape {\n  constructor() {\n    if (new.target === Shape) throw new Error('Shape is abstract')\n  }\n  area() { throw new Error('not implemented') }\n}\nclass Circle extends Shape { area() { return 1 } }\nnew Shape()   \u002F\u002F throws\nnew Circle()  \u002F\u002F\n```\n\nJavaScript has no built-in `abstract` keyword, so `new.target` (plus throwing\nfrom unimplemented methods) is the idiom for abstract base classes.\n",{"id":502,"difficulty":56,"q":503,"a":504},"reflect-construct","What is Reflect.construct?","The functional form of `new` — it invokes a constructor and optionally lets you\nspecify a different prototype (`newTarget`), useful in metaprogramming and for\nsubclassing built-ins.\n\n```js\nconst obj = Reflect.construct(Array, [1, 2, 3])   \u002F\u002F like new Array(1,2,3)\n\u002F\u002F third arg sets new.target \u002F the prototype to use:\nReflect.construct(Base, args, Derived)\n```\n\nIt's how you invoke a constructor dynamically (with an args array) and control\nthe resulting prototype — the building block frameworks use for advanced\ninstantiation.\n",{"id":506,"difficulty":35,"q":507,"a":508},"chaining-constructors","How do constructor functions call a parent constructor?","Call the parent with `Parent.call(this, args)` so the parent initializes the\nchild's instance fields.\n\n```js\nfunction Animal(name) { this.name = name }\nfunction Dog(name, breed) {\n  Animal.call(this, name)   \u002F\u002F parent sets this.name\n  this.breed = breed\n}\n```\n\nThis is the pre-class way to \"chain\" constructors. With classes, `super(name)`\ndoes the same thing, and is required before using `this` in a subclass.\n",{"id":510,"difficulty":43,"q":511,"a":512},"typeof-constructor","What does typeof return for a constructor or class?","`'function'` — both constructor functions and classes are functions under the\nhood.\n\n```js\nfunction Fn() {}\nclass Cls {}\ntypeof Fn    \u002F\u002F 'function'\ntypeof Cls   \u002F\u002F 'function'\n```\n\nClasses are special functions (strict mode, non-enumerable methods, must be\ncalled with `new`), but `typeof` doesn't distinguish them. To tell a class from\na regular function, you'd inspect the source or try calling without `new`.\n",{"id":514,"difficulty":35,"q":515,"a":516},"pure-constructor","Should constructors have side effects?","Keep constructors **focused on initialization**. Heavy work — network calls,\nDOM access, throwing on async failures — makes objects hard to create, test, and\nreason about.\n\n```js\n\u002F\u002F side-effectful constructor\nclass User { constructor(id) { this.data = fetch(`\u002Fu\u002F${id}`) } }\n\n\u002F\u002F construct simply, do work in a method\u002Fstatic factory\nclass User {\n  constructor(data) { this.data = data }\n  static async load(id) { return new User(await (await fetch(`\u002Fu\u002F${id}`)).json()) }\n}\n```\n\nA common pattern is a **static async factory** (`User.load`) that does the I\u002FO\nand then constructs a plain instance — constructors can't be async.\n",{"id":518,"difficulty":43,"q":519,"a":520},"new-object-vs-literal","Why prefer object literals over new Object?","`{}` is shorter, clearer, and slightly faster than `new Object()`, with no\ndownside. The same goes for `[]` over `new Array()` and `\u002Fregex\u002F` over\n`new RegExp()` for static patterns.\n\n```js\nconst a = {}            \u002F\u002F idiomatic\nconst b = new Object()  \u002F\u002F verbose, no benefit\n```\n\nUse `new` for types that genuinely need a constructor (`Date`, `Map`, `Set`,\n`Promise`, custom classes), and literals for the primitives-with-literals\n(objects, arrays, regexes).\n",{"id":522,"difficulty":35,"q":523,"a":524},"constructor-returning-this","How do you enable method chaining from a constructor's methods?","Have each method `return this`, so calls can be chained on the instance.\n\n```js\nclass QueryBuilder {\n  constructor() { this.parts = [] }\n  where(c) { this.parts.push(c); return this }\n  order(o) { this.parts.push(o); return this }\n  build() { return this.parts.join(' ') }\n}\nnew QueryBuilder().where('a=1').order('b').build()\n```\n\nReturning `this` (the instance) from methods is the builder\u002Ffluent pattern. It\nworks because methods are called on the instance, so `this` is consistent across\nthe chain.\n",{"id":526,"difficulty":56,"q":527,"a":528},"private-with-closures","How do you make private data with a constructor function?","Use closures: declare variables inside the constructor and expose only methods\nthat close over them — the variables aren't accessible as properties.\n\n```js\nfunction Counter() {\n  let count = 0                          \u002F\u002F private\n  this.increment = () => ++count\n  this.value = () => count\n}\nconst c = new Counter()\nc.increment()\nc.value()   \u002F\u002F 1\nc.count     \u002F\u002F undefined — truly private\n```\n\nThe trade-off: these methods are per-instance (closures), not shared on the\nprototype. Modern classes offer `#private` fields for shared-method privacy\nwithout closures.\n",{"description":32},"JavaScript constructor interview questions — what the new operator does, constructor functions, returning values, new.target, and common new-related bugs.","javascript\u002Fobjects\u002Fnew-constructors","The new Operator & Constructors","5aotjqlkjQas6w28TNEYJdSAiTtsD8hnRDnlHSFl6ys",1781808674571]