What Is The Purpose Of The 'Prototype' Property In JavaScript?

In JavaScript, the prototype property is used to add properties and methods to an object constructor function.

Every object in JavaScript has a prototype property, which is used to add new properties and methods to the object's type (or "class"). When a new object is created from a constructor function, it inherits the properties and methods from the constructor function's prototype property.

For example, let's say we have a constructor function for creating a Person object:

function Person(name) {
    this.name = name;
Person.prototype.greet = function() {
    console.log(`Hello, my name is ${this.name}.`);

In this example, we've added a greet method to the Person constructor function's prototype property. This means that every new Person object created from the Person constructor function will have a greet method inherited from the prototype property.

const person1 = new Person('Alice');
const person2 = new Person('Bob');

person1.greet(); // Hello, my name is Alice.
person2.greet(); // Hello, my name is Bob.

In this example, we create two new Person objects, person1 and person2, and call the greet method on each object. Both objects inherit the greet method from the Person constructor function's prototype property.

Using the prototype property can make your code more efficient, as it allows you to add properties and methods to all instances of an object without having to define them in each instance.

Similar Articles