What Are Prototypes in JavaScript? Why Are They Important?

What Are Prototypes in JavaScript? Why Are They Important?

Daily short news for you
  • swapy is a library that helps you create drag-and-drop actions to easily swap the positions of components.

    The library supports a wide range of platforms, making it perfect for building something personalized like a user’s Dashboard.

    » Read more
  • After waking up, I saw the news feed flooded with articles about Microsoft rewriting the TypeScript compiler - tsc in Go, achieving performance that is 10 times faster than the current one. Wow!

    But when I saw this news, the question immediately popped into my head: "Why not Rust?" You know, the trend of rewriting everything in Rust is hotter than ever, and it’s not an exaggeration to say that it's sweeping through the rankings of previous legacy tools.

    What’s even more interesting is the choice of Go - which supposedly provides the best performance to date - as they say. Many people expressed disappointment about why it wasn’t C# instead 😆. When something is too famous, everything is scrutinized down to the smallest detail, and not everyone listens to what is said 🥶

    Why Go? #411

    » Read more
  • I read this article Migrating Off Oh-My-Zsh and other recent Yak Shavings - the author essentially states that he has been using Oh-My-Zsh (OMZ) for a long time, but now the game has changed, and there are many more powerful tools that have come out, so he realizes, oh, he doesn't need OMZ as much anymore.

    I also tried to follow along because I find this situation quite similar to the current state. It was surprising to discover something new. I hope to soon write a post about this next migration for my readers 😁

    » 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...