[{"data":1,"prerenderedAt":150},["ShallowReactive",2],{"qa-\u002Fjavascript\u002Fobjects\u002Fnew-constructors":3},{"page":4,"siblings":134,"blog":147},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":20,"path":21,"questions":22,"related":125,"seo":126,"seoDescription":127,"stem":128,"subtopic":129,"topic":130,"topicSlug":131,"updated":132,"__hash__":133},"qa\u002Fjavascript\u002Fobjects\u002Fnew-constructors.md","New Constructors",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md","JavaScript","javascript",{},true,4,"\u002Fjavascript\u002Fobjects\u002Fnew-constructors",[23,27,32,37,41,45,49,53,57,61,65,69,73,77,81,85,89,93,97,101,105,109,113,117,121],{"id":24,"difficulty":14,"q":25,"a":26},"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":28,"difficulty":29,"q":30,"a":31},"constructor-function","easy","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":33,"difficulty":34,"q":35,"a":36},"forget-new","hard","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":38,"difficulty":34,"q":39,"a":40},"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":42,"difficulty":34,"q":43,"a":44},"new-target","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":46,"difficulty":14,"q":47,"a":48},"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":50,"difficulty":14,"q":51,"a":52},"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":54,"difficulty":14,"q":55,"a":56},"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":58,"difficulty":14,"q":59,"a":60},"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":62,"difficulty":29,"q":63,"a":64},"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":66,"difficulty":14,"q":67,"a":68},"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":70,"difficulty":14,"q":71,"a":72},"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":74,"difficulty":34,"q":75,"a":76},"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":78,"difficulty":34,"q":79,"a":80},"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":82,"difficulty":14,"q":83,"a":84},"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":86,"difficulty":34,"q":87,"a":88},"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":90,"difficulty":14,"q":91,"a":92},"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":94,"difficulty":34,"q":95,"a":96},"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":98,"difficulty":34,"q":99,"a":100},"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":102,"difficulty":14,"q":103,"a":104},"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":106,"difficulty":29,"q":107,"a":108},"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":110,"difficulty":14,"q":111,"a":112},"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":114,"difficulty":29,"q":115,"a":116},"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":118,"difficulty":14,"q":119,"a":120},"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":122,"difficulty":34,"q":123,"a":124},"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",null,{"description":11},"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","Objects & Prototypes","objects","2026-06-18","5aotjqlkjQas6w28TNEYJdSAiTtsD8hnRDnlHSFl6ys",[135,139,142,146],{"subtopic":136,"path":137,"order":138},"Objects & Properties","\u002Fjavascript\u002Fobjects\u002Fobjects-properties",1,{"subtopic":140,"path":141,"order":12},"Prototypes & the Prototype Chain","\u002Fjavascript\u002Fobjects\u002Fprototypes-chain",{"subtopic":143,"path":144,"order":145},"Prototypal Inheritance","\u002Fjavascript\u002Fobjects\u002Fprototypal-inheritance",3,{"subtopic":129,"path":21,"order":20},{"path":148,"title":149},"\u002Fblog\u002Fjavascript-new-operator-constructor-functions","The new Operator & Constructor Functions in JavaScript — How Object Creation Really Works",1781808676394]