JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Object Constructors


In JavaScript, object constructors are special functions used to create multiple similar objects efficiently. Instead of manually defining each object with the same structure, constructors allow you to define a blueprint that can be used to generate new objects with shared properties and methods. Understanding constructors is essential for object-oriented programming in JavaScript and for building scalable and maintainable applications.

In this tutorial, you will learn what object constructors are, how to use them, practical examples, common mistakes, best practices, and real-world applications.

Why Object Constructors Are Important

Object constructors are important because they:

  • Allow the creation of multiple objects with similar structure

  • Enable reusable code and avoid repetition

  • Support object-oriented programming principles

  • Allow initialization of properties at the time of object creation

  • Facilitate the use of methods that are shared across objects

Without constructors, developers would have to manually create multiple objects, leading to repetitive code and higher chances of errors.

Understanding Object Constructors

A constructor is a regular function, but by convention, its name starts with a capital letter. When called with the new keyword, it creates a new object with this pointing to that new object. Properties and methods can then be assigned to this inside the constructor.

Basic Syntax

function Student(name, age, course) {
    this.name = name;
    this.age = age;
    this.course = course;
}

Creating Objects Using Constructors

Once a constructor is defined, you can create objects using the new keyword:

const student1 = new Student("Aarushi", 20, "JavaScript");
const student2 = new Student("Priya", 22, "React");

console.log(student1.name); // Aarushi
console.log(student2.course); // React

Each object has its own set of properties, but they all share the same constructor structure.

Adding Methods to Constructors

Methods can be added inside the constructor, but it is more efficient to add them to the constructor’s prototype so that all objects share the same function rather than creating a new function for each object.

Method Inside Constructor

function Student(name, age) {
    this.name = name;
    this.age = age;
    this.greet = function() {
        console.log("Hello, my name is " + this.name);
    };
}

const student = new Student("Saanvi", 21);
student.greet(); // Hello, my name is Saanvi

While this works, each object has its own copy of the greet function, which can be memory inefficient.

Method on Prototype

function Student(name, age) {
    this.name = name;
    this.age = age;
}

Student.prototype.greet = function() {
    console.log("Hello, my name is " + this.name);
};

const student1 = new Student("Isha", 20);
const student2 = new Student("Priya", 22);

student1.greet(); // Hello, my name is Isha
student2.greet(); // Hello, my name is Priya

Using prototypes ensures that all objects created from the constructor share the same method, saving memory and maintaining consistency.

Using Constructor Parameters

Constructors can accept parameters to initialize object properties dynamically:

function Course(title, duration) {
    this.title = title;
    this.duration = duration;
}

const course1 = new Course("JavaScript Basics", "4 weeks");
const course2 = new Course("React Advanced", "6 weeks");

console.log(course1.title); // JavaScript Basics
console.log(course2.duration); // 6 weeks

This flexibility makes constructors ideal for creating multiple objects with similar properties but different values.

Inheritance with Constructors

You can implement inheritance by calling one constructor from another using call() or by setting the prototype.

function Person(name) {
    this.name = name;
}

function Teacher(name, subject) {
    Person.call(this, name);
    this.subject = subject;
}

Teacher.prototype = Object.create(Person.prototype);
Teacher.prototype.constructor = Teacher;

const teacher = new Teacher("Saanvi", "Math");
console.log(teacher.name); // Saanvi
console.log(teacher.subject); // Math

This allows the Teacher constructor to inherit properties from Person while adding its own properties.

Common Mistakes

  • Forgetting to use the new keyword, which causes this to refer to the global object

  • Adding methods inside the constructor instead of using the prototype, leading to memory inefficiency

  • Not capitalizing the constructor function name, which is a convention for readability

  • Overwriting the prototype incorrectly, which can break the constructor reference

  • Using constructors unnecessarily when object literals would suffice

Best Practices

  • Always capitalize constructor function names for clarity

  • Use prototypes for shared methods to optimize memory usage

  • Pass parameters to constructors to initialize objects dynamically

  • Use inheritance properly to extend functionality

  • Avoid using constructors for single, simple objects—object literals are sufficient in such cases

Real-World Applications

Object constructors are commonly used in:

  • Creating multiple user or student objects in applications

  • Modeling real-world entities like courses, books, or products

  • Implementing object-oriented design patterns

  • Building libraries or frameworks with reusable components

  • Managing application data in structured objects

Practical Examples

Example 1: Student Constructor

function Student(name, age, course) {
    this.name = name;
    this.age = age;
    this.course = course;
}

const student1 = new Student("Aarushi", 20, "JavaScript");
const student2 = new Student("Priya", 22, "React");

console.log(student1.name); // Aarushi
console.log(student2.course); // React

Example 2: Adding Methods via Prototype

Student.prototype.greet = function() {
    console.log("Hello, my name is " + this.name);
};

student1.greet(); // Hello, my name is Aarushi
student2.greet(); // Hello, my name is Priya

Example 3: Course Constructor

function Course(title, duration) {
    this.title = title;
    this.duration = duration;
}

Course.prototype.info = function() {
    console.log(this.title + " lasts " + this.duration);
};

const course1 = new Course("JavaScript Basics", "4 weeks");
course1.info(); // JavaScript Basics lasts 4 weeks

Example 4: Inheritance with Constructors

function Person(name) {
    this.name = name;
}

function Teacher(name, subject) {
    Person.call(this, name);
    this.subject = subject;
}

Teacher.prototype = Object.create(Person.prototype);
Teacher.prototype.constructor = Teacher;

Teacher.prototype.introduce = function() {
    console.log("I am " + this.name + ", teaching " + this.subject);
};

const teacher = new Teacher("Saanvi", "Math");
teacher.introduce(); // I am Saanvi, teaching Math

Summary of JavaScript Object Constructors

JavaScript object constructors provide a powerful way to create multiple objects with similar structures. They support dynamic initialization, reusable methods via prototypes, and object-oriented patterns such as inheritance. Proper use of constructors allows developers to write maintainable, scalable, and efficient code while avoiding repetition and memory issues. Mastering constructors is crucial for building professional JavaScript applications and understanding object-oriented programming concepts in JavaScript.


Practice Questions

  1. Basic Constructor
    Create a constructor Person with firstName, lastName, and age properties. Instantiate two objects and log their full details.

  2. Method Inside Constructor
    Add a method fullName() inside the Person constructor that returns the full name. Create an object and call this method.

  3. Prototype Method
    Move the fullName() method to the constructor's prototype and demonstrate that both instances can access it.

  4. Default Parameters
    Modify the Person constructor to set a default age of 18 if no age is provided. Create an object without passing age and log it.

  5. Multiple Instances
    Create a Product constructor with name, price, and quantity. Instantiate three different products and log their properties.

  6. Dynamic Method Using Parameters
    Add a method totalCost() in the Product constructor to calculate price * quantity. Call this method for each product.

  7. Checking Constructor
    Use instanceof to check if an object created with Person is actually an instance of Person and Object.

  8. Incorrect Use of new
    Call the Person constructor without new and explain the difference in behavior.

  9. Nested Objects in Constructor
    Create a Student constructor with a nested object marks containing math and science scores. Instantiate a student and log the marks.

  10. Adding Prototype Property
    Add a shared property species = "Homo sapiens" to the Person prototype. Log this property from multiple instances to show it is shared.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top