Topic 49 of 59 JavaScript Objects, Arrays & Advanced Data Structures Interactive Tutorial

JavaScript Constructor Functions: Creating Multiple Object Instances

23 mins read Last updated: 22 Aug 2026 14453 views
Quick Summary & Key Takeaway Target Skill Level: Beginner to Advanced ES6+

Bottom-Line Answer: JavaScript (JS) is a high-level, single-threaded, just-in-time (JIT) compiled programming language with first-class functions that conforms to the ECMAScript specification. It powers dynamic client-side web interactivity alongside HTML and CSS, and executes backend server runtimes via Node.js, Deno, and Bun.

Target Audience: Frontend developers, full-stack engineers, students & QA testers.
Prerequisites: Basic HTML semantics & fundamental CSS styling rules.
Primary Use Cases: Dynamic web UI, DOM manipulation, asynchronous REST APIs, Node.js backend services.

What is JavaScript Constructor Functions? Core Concept & Direct Summary

Core Objective & Problem Statement

How do constructor functions create object instances with new?

Direct Answer Summary
Constructor functions are named with PascalCase and invoked with new to create new instance objects.
class Student {
  constructor(name) {
    this.name = name;
  }
}
const s1 = new Student("Priya");

Here's the secret nobody tells beginners:JavaScript classes didn't exist until 2015.For twenty years, developers created objects-with-blueprints using something older and still everywhere:constructor functions.

And here's the bigger secret:a classisa constructor function wearing modern clothes.Under the hood, they're the same machinery. So learning constructor functions isn't learning a legacy relic — it's looking under the hood of what you already know, understanding whatnewactually does, and reading the millions of lines of older JavaScript still running the web. 🔧

Let's open the hood.

How Does JavaScript Constructor Functions Work? In-Depth Mechanics & Architecture

When new is used: 1. A new empty object is created; 2. Prototype is linked; 3. 'this' is bound to the object; 4. Object is returned.

What Is a Constructor Function?

Aconstructor functionis a regular function designed to be called withnew— its job is toconstructand initialize a new object.

script.js
Run Online
// 🏭 A constructor function — note the Capital name (convention!)function Student(name, age) {  this.name = name;              // "this" = the new object being built  this.age = age;}
// 🍪 Manufacturing instances with new:const s1 = new Student("Priya", 22);const s2 = new Student("Amit", 24);const s3 = new Student("Riya", 21);
console.log(s1.name);
// "Priya"console.log(s2.age);    // 24console.log(s3.name);   // "Riya" — three independent objects from one blueprint ✅

Sound familiar? It's exactly what theclassversion did. The conventions that mark a function as a constructor:

  1. Capitalized name—Student, notstudent(this is how humans know!)
  2. Assigned withthis.property =— building the new object
  3. Called withnew— never as a plain function
  4. Noreturn— the new object returns itself automatically

What DoesnewActually Do? (The 4 Steps) 🎬

This is the interview question — and Lesson 29's Rule 1 explained fully. When you writenew Student("Priya", 22), JavaScript performs four steps behind the curtain:

script.js
Run Online
const s1 = new Student("Priya", 22);

Step by step:

script.js
Run Online
① 🆕 A brand-new empty object is created: {
}② 🔗 The object is linked to Student's prototype   (more on prototypes in a moment!)
③ 🎯 The constructor runs with `this` = that new object:   this.name = "Priya"   →   { name: "Priya" }   this.age  = 22        →   { name: "Priya", age: 22 }
④ 📤 The finished object is automatically returned   (unless you explicitly return a different object — rare!)

Proof you can see:

script.js
Run Online
function Student(name) {
  this.name = name;
  console.log("constructor ran! this =", this);
  // watch step ③ happen}
  const s1 = new Student("Priya");
  // "constructor ran! this = Student { name: 'Priya' }" ✅
  console.log(s1 instanceof Student);
  // true — the prototype link from step ② ✅

Once you see these four steps,newstops being magic — it's a fixed recipe:create → link → build → return.


⚠️ The Classic Trap: Forgettingnew

What happens if you call a constructor like a normal function?

script.js
Run Online
function Student(name) {
  this.name = name;
}const s = Student("Priya");
// 😱 no "new"!
console.log(s);
// undefined — nothing was returned!console.log(window.name);        // "Priya" 💀 — leaked onto the GLOBAL object!

Withoutnew, there's no new object — sothisfalls back to the global object (Lesson 29's Rule 4!), andthis.name = "Priya"polluteswindow.name. The bug of the 2000s. 🐛

Modern protections:

  • 🚨Strict mode(Lesson 36):thisisundefined→ you get an immediate TypeError instead of silent global pollution
  • 🏛️Classes:Student("Priya")withoutnewthrows a TypeErroralways— classes make the trap impossible

This is one big reason classes won: they turned a silent disaster into a loud, helpful error.


Methods: The Prototype Difference 🧬

The naive way to add methods has a hidden flaw:

script.js
Run Online
// ⚠️ The wasteful way:function Student(name) {  this.name = name;  this.greet = function() {              // defined INSIDE the constructor    return `Hi, I'm ${this.name} 👋`;  };}
const s1 = new Student("Priya");
const s2 = new Student("Amit");
console.log(s1.greet === s2.greet);
// false 😱 — two SEPARATE copies!

Every instance carries itsown copyof the same function. Create 10,000 students → 10,000 identicalgreetfunctions hogging memory.

The prototype fix — one shared copy for everyone:

script.js
Run Online
function Student(name) {
  this.name = name;
  // ✅ data per instance}
  // ✅ methods go on the PROTOTYPE — shared by ALL instances:Student.prototype.greet = function() {  return `Hi, I'm ${this.name} 👋`;};
  const s1 = new Student("Priya");
  const s2 = new Student("Amit");
  console.log(s1.greet());
  // "Hi, I'm Priya 👋"console.log(s2.greet());              // "Hi, I'm Amit 👋"console.log(s1.greet === s2.greet);   // true ✅ — ONE shared copy!

How it works:when you calls1.greet(), JavaScript doesn't findgreetons1itself — so it follows theprototype link(step ②!) up toStudent.prototype, where it lives. Every instance shares one copy. This lookup chain is JavaScript's actual inheritance engine.

🔑 The reveal:class Student { greet() {…} }from Lesson 23 doesexactly this— methods defined in a class body are placed on the prototype automatically. Classes didn't replace prototypes; they just made them pretty.


Constructor Functions vs Classes 🥊

The full comparison — another interview favorite:

script.js
Run Online
// 🏭 Constructor function style (pre-2015):
function Student(name) {
  this.name = name;
}Student.prototype.greet = function() {
  return `Hi, I'm ${this.name}`;
};
// 🏛️ Class style (2015+) — same machinery, cleaner wrapping:
class Student {
  constructor(name) {
    this.name = name;
  } greet() {
    return `Hi, I'm ${this.name}`;
  }
}
Constructor FunctionClass
Era1995–20152015+ ✅
Callable withoutnew?Yes — dangerous silent bug 💀❌ Throws TypeError (safer!)
Methods live onFn.prototype(manual)Prototype (automatic) ✅
Hoisted?✅ Yes (function declaration)❌ TDZ — like let/const (Lesson 40!)
Inheritance syntaxManual prototype wiring 😬extends/super✅
Underneath—IS a constructor function🎭

Proof of that last row:

script.js
Run Online
class Student {
}console.log(typeof Student);
// "function" 😮 — classes are functions underneath!

Verdict:writeclassesin new code (safer, cleaner). Understandconstructor functionsto read older code, answer interviews, and truly grasp prototypes.


instanceof: Checking an Object's Origin 🛂

How do you verify which blueprint built an object?

script.js
Run Online
function Student(name) {
  this.name = name;
}function Teacher(name) {
  this.name = name;
}const s1 = new Student("Priya");
console.log(s1 instanceof Student);
// true ✅
console.log(s1 instanceof Teacher);
// false
console.log(s1 instanceof Object);
// true — everything descends from Object!

instanceoffollows the prototype chain — it's how real apps check whether data came from the expected blueprint before trusting it.


Built-In Constructors You've Been Using All Along 😲

Surprise — JavaScript's own types are constructor functions:

script.js
Run Online
new Array(1, 2, 3);
// [1, 2, 3]  (literal [] is the shortcut)
new Object();
// {}         (literal {} is the shortcut)
new Date();
// today's date (Lesson 33!)
new Promise((res, rej) => {
});
// Lesson 26!
new Map();
// a Map

Every[]you've ever written secretly runs theArrayconstructor. The literal syntaxes are just shortcuts — which is whytypeof []is"object"andArray.isArray([])exists (Lesson 5's quirk explained at last!).

⚠️ Never construct primitives:new String("hi"),new Number(5),new Boolean(true)createwrapper objectswith bizarre behavior (typeof new String("hi")is"object"! 😱). Always use the plain literals:"hi",5,true. (Remember Lesson 11'snew Boolean(false)trap!)


🛠️ Mini Project: RPG Character Factory ⚔️

Lesson 23's RPG — rebuilt the old-school way, so you canfeelthe equivalence:

script.js
Run Online
// ⚔️ Character factory — constructor + prototype (pre-class style)
function Character(name, health) {
  this.name = name;
  this.health = health;
}// Shared methods on the prototype — ONE copy for all characters:
Character.prototype.attack = function(target) {
  target.health -= 10;
  console.log(`⚔️ ${this.name} hits ${target.name}! (${target.name}: ${target.health} HP)`);
};
Character.prototype.isAlive = function() {
  return this.health > 0;
};
// 🍪 Manufacture the fighters:
const hero = new Character("Arjun", 100);
const villain = new Character("Duryodhan", 80);
hero.attack(villain);
// ⚔️ Arjun hits Duryodhan! (70 HP)
villain.attack(hero);
// ⚔️ Duryodhan hits Arjun! (90 HP)
hero.attack(villain);
// ⚔️ 60 HP
console.log(hero.isAlive());
// true
console.log(hero.attack === villain.attack);
// true — ONE shared method ✅
console.log(hero instanceof Character);
// true ✅

The class version from Lesson 23 did the identical thing—constructor()↔ the function body, class methods ↔ prototype methods. Same engine, modern paint job. 🏆

Common Beginner Mistakes (And Fixes)

❌ Mistake🔍 What Happens✅ Fix
Calling withoutnewSilent global pollution (or TypeError in strict)Alwaysnew Constructor()
Lowercase constructor namesHumans (and linters) can't spot constructorsCapitalize:Student, notstudent
Methods inside the constructorEvery instance gets its own copy — wasted memoryPut methods on.prototype
returning primitives from constructorsConfusing behavior — return ignored for objectsDon't return; letnewdeliver
new String()/new Number()Wrapper objects with weird typeofPlain literals:"str",42
Assuming constructors are "dead tech"Can't read older codebases/interviews 😬Learn them — classes sit on top

Quick Self-Check: Lesson 48 Quiz 🧠

  1. What are the four steps thenewkeyword performs?
  2. What's the output and why?
    script.js
    Run Online
    function Pet(name) {
      this.name = name;
    }const p = Pet("Bruno");
    console.log(p);
  3. Why do methods belong onConstructor.prototypeinstead of inside the constructor?
  4. What's the output?console.log(typeof class Foo {});
  5. What doess1 instanceof Studentactually check?

(Answers: 1. ① Create empty object ② Link it to the constructor's prototype ③ Run the constructor with this = the new object ④ Return the object automatically · 2. undefined — without new, no object is built/returned; worse, this.name polluted the global object (in non-strict mode) · 3. Constructor-body methods create a separate copy per instance; prototype methods are shared by all instances — one copy, less memory · 4. "function" — classes ARE constructor functions underneath · 5. Whether Student.prototype appears anywhere in s1's prototype chain — i.e., whether that blueprint built it)

JavaScript Decision Matrix & Syntax Comparison

Understanding the mechanical differences between variable declarations and execution environments is critical for writing performant, bug-free modern JavaScript.

Variable Declarations: var vs let vs const
Feature / Propertyvar (Legacy ES5)let (Modern ES6+)const (Modern ES6+)
ScopeFunction ScopeBlock Scope ({})Block Scope ({})
Hoisting BehaviorHoisted (initialized as undefined)Hoisted (Temporal Dead Zone - ReferenceError)Hoisted (Temporal Dead Zone - ReferenceError)
Reassignable✓ Yes✓ Yes✗ No (Immutable binding)
Redeclarable in Same Scope✓ Yes (Error-prone)✗ No (SyntaxError)✗ No (SyntaxError)
Window Object BindingCreates property on windowDoes not attach to windowDoes not attach to window
Environment Decision Matrix: Browser Client-Side vs Node.js Server-Side
DimensionClient-Side (Web Browser)Server-Side (Node.js / Deno)
Global Objectwindow, document, navigatorglobal, process, globalThis
DOM & UI Manipulation✓ Full access (document.querySelector)✗ No DOM (Headless / Non-UI)
File System & OS Access✗ Blocked (Sandboxed security)✓ Full access (fs, os, child_process)
Primary FocusInteractive UI, animations, client stateREST APIs, microservices, databases, I/O streaming

Runnable JavaScript Code Example & Practical Implementation

script.js
Run Online
function Person(name, age) {
  this.name = name;
  this.age = age;
}Person.prototype.sayHi = function() {
  console.log(`Hi, I am ${this.name}`);
};
const user1 = new Person('Alice', 25);
user1.sayHi();

Frequently Asked Questions & Technical Interview Insights

Technical Interview & Viva Questions

Frequently asked questions for frontend & full-stack roles
Q

Q: What happens if you call a constructor function without the new keyword?

A: In non-strict mode, 'this' binds to the global object, creating unintended global variables and returning undefined.

Related Tools, Tutorials & Authoritative References

Recommended Interactive Tools

Authoritative Standards & Citations