JAVASCRIPT • OBJECT-ORIENTED PROGRAMMING (INTRO)

Constructor Functions — Use constructor functions conceptually (intro)

Learn how constructor functions serve as reusable blueprints for creating multiple objects that share the same structure.

Historical Context & Motivation

In the early days of programming, developers wrote code that handled one thing at a time. If you needed to represent a student, you'd create a few variables like studentName and studentGrade. But what happened when you needed to represent 30 students? You'd suddenly have 60 or more loose variables floating around, and the code became nearly impossible to manage. This frustration led programmers to develop the idea of object-oriented programming (OOP), where related data and behavior are bundled together into organized structures called objects.

JavaScript, created by Brendan Eich in 1995, took a unique approach to OOP. Rather than using traditional class-based systems found in languages like Java and C++, JavaScript relied on constructor functions and prototypes to create and organize objects. Constructor functions became the primary way JavaScript developers built reusable templates for creating many similar objects efficiently.

1967
Simula Introduces OOP
Norwegian computer scientists Ole-Johan Dahl and Kristen Nygaard create Simula, the first language to introduce classes and objects, laying the groundwork for all object-oriented programming.
1995
JavaScript Is Born
Brendan Eich designs JavaScript in just 10 days. Instead of classes, the language uses constructor functions and prototypes to achieve object-oriented patterns.
1997
ECMAScript Standard
JavaScript is standardized as ECMAScript. Constructor functions and the new keyword become officially defined parts of the language specification.
2015
ES6 Adds Class Syntax
ECMAScript 2015 introduces the class keyword, but under the hood it still uses constructor functions and prototypes. Understanding constructors remains essential.

The central question that constructor functions solve is straightforward: How can we create many objects that share the same structure without writing repetitive code? Instead of manually typing out each object one by one, a constructor function acts like a factory that stamps out consistent objects on demand.

Core Principles & Definitions

Before we dive into code, let's establish the key ideas behind constructor functions. A constructor function is a regular JavaScript function that is designed to be called with the new keyword. When called this way, it automatically creates a brand-new object, assigns properties to it, and returns that object. By convention, constructor function names start with a capital letter (like Student instead of student) so that other developers can instantly recognize it as a constructor.

1

Blueprint Pattern

A constructor function defines the shape that every object created from it will share. It specifies which properties and values each object should have upon creation.
2

The new Keyword

Calling a function with new triggers special behavior: JavaScript creates an empty object, sets this to point to that object, runs the function body, and returns the object.
3

The this Keyword

Inside a constructor, this refers to the brand-new object being created. Using this.name = name attaches a property called name to that specific object.
4

Instances

Each object created by a constructor is called an instance. Every instance has the same property names but can hold different values, just like each student has a name but each name is different.
5

Capital Letter Convention

Constructor functions use PascalCase (e.g., Car, Player) to distinguish them from regular functions. This is a naming convention, not a language rule, but nearly all JavaScript developers follow it.
✦ KEY TAKEAWAY
Think of a constructor function like a cookie cutter. The cookie cutter itself isn't a cookie — it's a tool that defines the shape. Every time you press it into dough, you get a new cookie with the same shape but you can decorate each one differently. The constructor function is your cookie cutter, and each object it creates is a unique cookie (instance) with its own specific data.

Visual Explanation

The diagram below illustrates how a single constructor function produces multiple distinct objects. Notice how the constructor function sits at the top as the blueprint, and each call with new generates a separate instance with its own property values.

The violet box at the top represents the constructor function — the blueprint. Each cyan arrow represents a new call that produces a separate instance (pink, amber, and emerald boxes). Each instance has the same property names but different values.

As you can see, the constructor function Student defines two properties: name and grade. Every time we call new Student(...), JavaScript creates a fresh object and fills in those properties with whatever arguments we pass. The three resulting instances are completely independent — updating Alice's grade will not change Bob's or Carlos's.

How Constructor Functions Work Step by Step

When you write new Student("Alice", 10), JavaScript performs four hidden steps behind the scenes. Understanding these steps demystifies what new actually does and why the this keyword behaves the way it does inside a constructor.

The Four Steps of new

  1. Step 1 — Create: JavaScript creates a brand-new, empty object {} in memory.
  2. Step 2 — Link: The new object is linked to the constructor's prototype (an advanced topic we'll explore later).
  3. Step 3 — Bind this: Inside the constructor function, this is set to point at the newly created empty object. Every this.property = value statement attaches data to that object.
  4. Step 4 — Return: The fully formed object is automatically returned, even though you don't write a return statement.
The top row shows the four steps JavaScript performs when it encounters new. The bottom panel zooms into Step 3, showing how each this.property assignment adds data to the new object. The green box at the bottom shows the final returned object.
⚠️ Common Mistake
If you forget the new keyword and just call Student("Alice", 10) as a regular function, this will not point to a new object. In non-strict mode it would point to the global window object, which causes unexpected bugs. Always remember to use new!

Anatomy of a Constructor Function

Let's break down every part of a constructor function's syntax so you can confidently read and write your own. We'll use a Car constructor as our running example, since most students are familiar with how cars have different makes, models, and years.

Anatomy of a constructor function and its usage
Code PartExampleWhat It Does
Function keywordfunctionDeclares a function (the constructor)
Constructor name (PascalCase)CarCapital letter signals this is a constructor, not a regular function
Parameters(make, model, year)Data that will be unique to each instance
Property assignmentthis.make = make;Attaches the passed-in value to the new object
Creating an instancenew Car("Toyota", "Camry", 2023)Triggers the 4-step process and returns a new Car object
Resulting object{ make: "Toyota", model: "Camry", year: 2023 }A plain JavaScript object with three properties

One important distinction to understand is the difference between a constructor function (the template) and an object literal (a one-off object). An object literal like { make: "Toyota", model: "Camry", year: 2023 } creates a single object with no reusable template. A constructor function lets you stamp out as many similar objects as you want, each time passing in different arguments.

💡 When to Use a Constructor
Use a constructor function whenever you need to create two or more objects that share the same structure. If you only need one object, an object literal is simpler. Think of it this way: a single poster can be hand-drawn, but a whole batch of posters needs a printing press (the constructor).

Worked Example — Building a Game Character Constructor

Let's walk through a complete example where we build a GameCharacter constructor function. Imagine you're making a simple RPG game and you need to create multiple characters, each with their own name, health points, and attack power.

Creating a GameCharacter Constructor
1
Step 1 — Define the Constructor FunctionStart by writing a function with a PascalCase name and listing the parameters for properties you want each character to have. Inside the function body, use this to attach each parameter as a property.
function GameCharacter(name, health, attackPower) { this.name = name; this.health = health; this.attackPower = attackPower; }
2
Step 2 — Create the First InstanceUse the new keyword followed by the constructor name and pass in specific values for this character. Store the result in a variable.
const warrior = new GameCharacter("Thorin", 100, 25);
3
Step 3 — Create a Second InstanceCall the same constructor again with different arguments to create a completely separate character object.
const mage = new GameCharacter("Elara", 70, 40);
4
Step 4 — Access PropertiesUse dot notation to read properties from each instance. Each object has its own separate data.
console.log(warrior.name); // "Thorin" console.log(mage.health); // 70
5
Step 5 — Verify IndependenceModify one instance's property and confirm the other instance is unaffected. This proves each instance is a separate object in memory.
warrior.health = 85; console.log(warrior.health); // 85 console.log(mage.health); // 70 (unchanged)
✦ KEY TAKEAWAY
Each call to new GameCharacter(...) is like filling out a fresh registration form at a doctor's office. The form (constructor) has the same blank fields every time, but each patient (instance) fills them in with their own personal information. Changing one patient's form doesn't alter anyone else's records.

Constructor Functions vs. Object Literals

You might wonder why we need constructor functions at all, since you can already create objects using object literals (the curly-brace {} syntax). The table below highlights the key differences. In short, object literals work well for one-off objects, but constructor functions shine when you need to produce many objects of the same type.

Comparing object literals and constructor functions
FeatureObject LiteralConstructor Function
ReusabilitySingle use — creates one objectReusable — produces as many objects as needed
Syntaxconst dog = { name: "Rex", age: 3 };const dog = new Dog("Rex", 3);
Structure enforcementNo guarantee — each literal can have different propertiesConsistent — every instance shares the same property names
Identifying typeNo built-in way to check what "type" the object isinstanceof operator can identify the constructor
Best forConfiguration objects, one-time data containersEntities you create many of: users, products, game characters
🔑 WHEN TO CHOOSE WHICH
If you're writing a grocery list for one shopping trip, you'd just scribble it on a piece of paper (object literal). But if you run a store and need to generate hundreds of product records with the same fields — name, price, quantity — you'd design a form template (constructor function). Use the right tool for the job: object literals for one-offs, constructors for mass production.

Connection to ES6 Classes and Beyond

In 2015, JavaScript introduced the class keyword as part of ES6 (also called ECMAScript 2015). If you've seen class-based code in other languages or tutorials, you might wonder if constructor functions are outdated. The answer is no — ES6 classes are syntactic sugar that wraps the same constructor function and prototype mechanism in a cleaner, more familiar syntax. Learning constructor functions first gives you a deeper understanding of what classes actually do behind the scenes.

Constructor functions vs. ES6 class syntax
FeatureConstructor Function (ES5)Class Syntax (ES6+)
Defining a templatefunction Dog(name) { this.name = name; }class Dog { constructor(name) { this.name = name; } }
Creating an instancenew Dog("Rex")new Dog("Rex")
Under the hoodUses prototype chain directlyAlso uses prototype chain — just cleaner syntax
InheritancePrototype-based (manual setup)extends keyword makes inheritance intuitive
Why learn it?Foundation — explains what JS actually doesModern preference — used in most codebases today

As you progress in JavaScript, you'll learn about prototypes (which let instances share methods efficiently), inheritance (which lets one constructor build upon another), and encapsulation (which hides an object's internal data from outside code). All of these concepts build directly on the constructor function foundation you're learning today. Think of this lesson as laying the first row of bricks — every advanced OOP topic stacks on top of it.

Practice Problems

PROBLEM 1 — CONCEPTUAL
In your own words, explain the difference between a constructor function and an instance. Use an analogy to support your explanation.
PROBLEM 2 — BASIC CALCULATION
Given the following constructor function, what will console.log(book1.title) and console.log(book2.pages) output? function Book(title, author, pages) { this.title = title; this.author = author; this.pages = pages; } const book1 = new Book("Dune", "Frank Herbert", 412); const book2 = new Book("1984", "George Orwell", 328);
PROBLEM 3 — INTERMEDIATE
Write a constructor function called Smartphone that takes three parameters: brand, model, and storageGB. Then create two instances: one for an iPhone 15 with 256 GB, and one for a Samsung Galaxy S24 with 128 GB. Finally, write a line of code that changes the iPhone's storage to 512.
PROBLEM 4 — APPLIED
You're building a classroom attendance app. Design a constructor function called Student with properties for firstName, lastName, grade, and isPresent (which should default to false for every new student, regardless of what the caller passes in). Explain how you enforce that default and create one example instance.
PROBLEM 5 — CRITICAL THINKING
A classmate writes the following code and says "it works the same as a constructor function." Evaluate whether they're correct, and explain what advantages or disadvantages their approach has compared to a proper constructor function. function createPet(name, species) { return { name: name, species: species }; } const pet1 = createPet("Buddy", "Dog");

Lesson Summary

A constructor function is a reusable blueprint for creating JavaScript objects. Written with a PascalCase name and invoked with the new keyword, it triggers a four-step process: JavaScript creates an empty object, links it to a prototype, binds this to the new object so that property assignments stick, and automatically returns the finished object. Each object produced is called an instance — it shares the same property names defined in the constructor but holds its own unique values.

Constructor functions solve the problem of code duplication when you need many objects with the same structure. They differ from object literals (best for one-off objects) and serve as the foundation for the modern ES6 class syntax, which is syntactic sugar over the same mechanism. Mastering constructors prepares you for prototypes, inheritance, and encapsulation — the pillars of object-oriented JavaScript.

Varsity Tutors • JavaScript • Constructor Functions — Use constructor functions conceptually (intro)