What Are Prototypes in JavaScript? Why Are They Important?

What Are Prototypes in JavaScript? Why Are They Important?

Daily short news for you
  • Dedicating to those who may not know, snapdrop is an open-source application that helps share data with each other if they are on the same Wifi network, operating based on WebRTC.

    Why not just use AirDrop or Nearby Share instead of going through this hassle? Well, that’s only if both parties are using the same operating system. Otherwise, like between Android and iOS, or MacOS and Linux or Windows... At this point, snapdrop proves to be extremely useful 😁

    » Read more
  • 24 interesting facts about SQLite Collection of insane and fun facts about SQLite. I have to say it's really amazing 🔥

    » Read more
  • bolt.new is so awesome, everyone! It can handle all types of Front-end work. The thing is, I was out of ideas, so I went there and described in detail the interface I wanted, the more detailed the better, and it just generated it for me, which was surprising. Although it's not perfect, it's very similar to what I imagined in my head, and making adjustments is easy. By default, this tool generates code for React or something, so if you don't want that, just ask it to generate code for the platform you're using.

    The downside is that each subsequent prompt will replace all the old code -> it consumes tokens. You probably can only request a few times before running out of the free tokens for the day. The upside is they are currently giving away 2 million free tokens for everyone. Go get yours now 🥳

    » Read more

The Issue

If you've worked with object-oriented programming languages before, the class syntax is the clearest way to declare a new object. JavaScript is also considered an object-oriented programming language, but if you're an early JavaScript developer from around a decade ago, it didn't have the class syntax. Instead, it supported inheritance through prototypes, which had a somewhat different syntax compared to OOP in most other languages and wasn't highly regarded for its powerful OOP features.

In recent years, ES6 introduced the class keyword to make it easier for developers to write OOP-style code or, in other words, make it more friendly for those accustomed to the OOP syntax. However, at its core, it's still powered by prototypes. In this article, we'll explore what prototypes are and why they are important in JavaScript.

What Are Prototypes?

Prototypes are the mechanism by which JavaScript objects inherit features from one another. Every object created from a constructor function has a default prototype, which is the prototype of that constructor function.

Every object in JavaScript has properties and methods integrated into it, called the prototype. The prototype itself is also an object, so it has its own prototype, creating a prototype chain. This chain only ends when the prototype is null.

Prototypes define the properties and methods that objects created from that constructor function can access. When an object is created, it inherits all properties and methods from the prototype of the constructor function.

For example:

const myObject = {
  name: "2coffee",
  greet() {
    console.log(`Greetings from ${this.name}`);
  },
};

myObject.greet(); // Greetings from 2coffee

In the example above, greet() is a method of myObject, so it can call that method. However, besides greet(), myObject is an Object, so it inherits the entire prototype of Object. The prototypes within myObject would look something like this:

__defineGetter__
__defineSetter__
__lookupGetter__
__lookupSetter__
__proto__
name
constructor
greet
hasOwnProperty
isPrototypeOf
propertyIsEnumerable
toLocaleString
toString
valueOf

myObject has access to all of these prototypes, such as calling the toString method.

myObject.toString(); // "[object Object]"

When trying to access a property of an object, if the property isn't found within the object itself, it will look for it in the prototype of the parent object. This continues until the property is found or the prototype chain ends, returning undefined.

For example, with a Date object in JavaScript. Date is an instance of Object, and Date also has its own prototype, so an object created from Date will have at least 3 layers of prototypes.

Prototypes in Date object

What Are Prototypes Used For?

As mentioned earlier, prototypes are primarily used for inheritance in object-oriented programming. Using prototypes in JavaScript allows us to efficiently add properties and methods to objects. Instead of creating methods and properties for each object, we can add them to the prototype of the constructor function, allowing all objects created from that constructor function to access them.

For example, consider a program that defines a Geometry class with two methods: calculatePerimeter and calculateArea. Two classes, Square and Circle, inherit from Geometry through prototypes, written as follows:

// Define the Geometry class
function Geometry() {}

// Method to calculate perimeter
Geometry.prototype.calculatePerimeter = function() { return; }

// Method to calculate area
Geometry.prototype.calculateArea = function() { return; }

// Define the Square class inheriting from Geometry
function Square(sideLength) {
  this.sideLength = sideLength;
}

Square.prototype = Object.create(Geometry.prototype);
Square.prototype.constructor = Square;

// Override the calculatePerimeter method for Square
Square.prototype.calculatePerimeter = function() {
  return this.sideLength * 4;
}

// Override the calculateArea method for Square
Square.prototype.calculateArea = function() {
  return this.sideLength * this.sideLength;
}

// Define the Circle class inheriting from Geometry
function Circle(radius) {
  this.radius = radius;
}

Circle.prototype = Object.create(Geometry.prototype);
Circle.prototype.constructor = Circle;

// Override the calculatePerimeter method for Circle
Circle.prototype.calculatePerimeter = function() {
  return 2 * Math.PI * this.radius;
}

// Override the calculateArea method for Circle
Circle.prototype.calculateArea = function() {
  return Math.PI * this.radius * this.radius;
}

Prototypes and Classes

Since ES6, JavaScript introduced a new syntax for inheritance, the class keyword. By using this new syntax, it makes us more familiar with object-oriented programming syntax from other languages.

For example, the same program as above but written using classes looks much cleaner:

// Define the Geometry class
class Geometry {
  calculatePerimeter() { return; }

  calculateArea() { return; }
}

// Define the Square class inheriting from Geometry
class Square extends Geometry {
  constructor(sideLength) {
    super();
    this.sideLength = sideLength;
  }

  calculatePerimeter() {
    return this.sideLength * 4;
  }

  calculateArea() {
    return this.sideLength * this.sideLength;
  }
}

// Define the Circle class inheriting from Geometry
class Circle extends Geometry {
  constructor(radius) {
    super();
    this.radius = radius;
  }

  calculatePerimeter() {
    return 2 * Math.PI * this.radius;
  }

  calculateArea() {
    return Math.PI * this.radius * this.radius;
  }
}

Even though class was introduced in ES6, it still has some limitations compared to OOP in pure object-oriented languages like Java and C#. Partly because class is still based on prototypes, but it was created to simplify code complexity, making it more readable and concise.

The Importance of Prototypes

Prototypes are a crucial concept in JavaScript because they allow us to create objects with inheritance and reuse code efficiently.

Objects created from the same constructor function can share properties and methods defined in the prototype of that constructor function. This reduces code duplication and saves memory for your application.

If you look closely, you'll notice that almost everything in JavaScript is rooted in prototypes. Creating a new object, it inherits the entire prototype from Object. Creating a function, it inherits the entire prototype from Function, and so on.

Prototype of an object

Additionally, using prototypes allows us to create child objects that inherit properties and methods from parent objects. This enhances code reusability, minimizes duplication, and improves maintenance of your application.

Furthermore, prototypes provide a way to extend existing objects in JavaScript. By adding properties and methods to an object's prototype, we can expand the functionality of that object without modifying the original source code.

Therefore, prototypes are a fundamental concept in JavaScript and one of the ways to increase flexibility, efficiency, and maintainability in the long run.

Conclusion

Prototypes are the mechanism by which JavaScript objects inherit features from one another. Early JavaScript developers had to write inheritance based on prototypes. In recent years, ES6 introduced the class syntax, making it friendlier for those accustomed to object-oriented programming syntax. Prototypes are a fundamental concept in JavaScript, as nearly everything, such as Object, Function, and more, is built on prototypes. Understanding the essence of prototypes will help you learn more advanced concepts in the future.

References:

Premium
Hello

5 profound lessons

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (0)

Leave a comment...
Scroll or click to go to the next page