What Are Prototypes in JavaScript? Why Are They Important?

What Are Prototypes in JavaScript? Why Are They Important?

Daily short news for you
  • Thank you to threads.net from Meta for being the inspiration behind this section on my blog. Initially, I was a bit skeptical about whether creating short posts like this would attract users, whether anyone would come back to read day after day, or if it would all just be like building sandcastles by the sea. As I have often mentioned, creating a feature is not difficult, but how to operate it effectively is what truly matters.

    Now, time has proven everything. The Short Posts section consistently ranks in the top 5 most visited pages of the day/week/month. This means that readers have developed a habit of returning more often. How can I be so sure? Because this section is almost completely unoptimized for SEO on search engines like Google.

    Let me take you back a bit. In the beginning, I was very diligent in posting on threads.net in the hope of attracting many followers, so that I could subtly introduce them to become users of my blog. However, as time went on, I increasingly felt "exhausted" because the Threads algorithm became less and less aligned with my direction. In other words, the content created was not popular.

    For example, my posts often lean towards sharing information, news, or personal experiences drawn from learning or doing something. It seems that such posts are not highly regarded and often get buried after just over... 100 views. Hmm... Could the problem be me? Knowing this, why not change the content to be more suitable for the platform?

    I have observed Threads, and the content that spreads the most easily often contains controversial elements or a prejudice about something, sometimes it’s simply stating something "naively" that they know will definitely get interactions. However, I almost do not like directing users towards this kind of content. People might call me stubborn, and I accept that. Everyone has different content directions and audiences; the choice is theirs.

    So, from then on, I mainly write here. Only occasionally, if I find something very interesting, do I go on Threads to "show off." Here, people still come to read daily; no matter who you are, I am sure that you can recognize the message I want to convey through each post. At the very least, we share a common direction regarding content. Sometimes, the scariest thing is not that no one reads what you write, but that they read it and then forget it in an instant. Quantity is important, but quality is what brings us closer together.

    Thank you all 🤓

    » Read more
  • Zed is probably the most user-centric developer community on the planet. Recently, they added an option to disable all AI features in Zed. While many others are looking to integrate deeper and do more with AI Agents. Truly a bold move 🤔

    You Can Now Disable All AI Features in Zed

    » Read more
  • Today I have tried to walk a full 8k steps in one session to show you all. As expected, the time spent walking reached over 1 hour and the distance was around 6km 🤓

    Oh, in a few days it will be the end of the month, which means it will also mark one month since I started the habit of walking every day with the goal of 8k steps. At the beginning of next month, I will summarize and see how it goes.

    » 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

The secret stack of Blog

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click now!

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, 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...