DEV Community


Posted on

What is Prototype? Prototype in JavaScript

In JavaScript, prototypes are mechanisms by which objects can inherit properties from other objects. This is an important part of JavaScript's object-oriented programming (OOP) functionality.

To understand in Easy language, Think of prototypes in JavaScript like a blueprint or a guide. Every object in JavaScript has a link to its prototype object, where this prototype object has a prototype of its own, creating what we call a prototype chain.

When we try to access a property or method on an object, JavaScript will first look if that property or method is directly on the object. If not, it looks to the object's prototype (its blueprint), and then the prototype's prototype, and so on up the chain until it either finds what it's looking for or reaches the end of the chain (which is usually the base Object prototype).

Here's a simple example: Let's imagine we have a car object.

let car = {
  make: 'Toyota',
  model: 'Camry'
Enter fullscreen mode Exit fullscreen mode

We can create a prototype for our car that describes things all cars can do.

car.__proto__ = {
  startEngine: function() {
    return 'Engine started';
Enter fullscreen mode Exit fullscreen mode

In this example, startEngine is a method on our car's prototype. Now, we can call this method on car, even though we didn't define it directly on car:

console.log(car.startEngine());  // Outputs: 'Engine started'
Enter fullscreen mode Exit fullscreen mode

When we call car.startEngine(), JavaScript first looks if startEngine is a method directly on car. It's not, so JavaScript looks at car's prototype and finds startEngine there.

So, prototypes are like a backup for objects. If an object can't do something, it looks to its prototype for help.

you want to know more about OOps or Prototype in Advance

Thank you for reading. I encourage you to follow me on Twitter where I regularly share content about JavaScript and React, as well as contribute to open-source projects. I am currently seeking a remote job or internship.




Top comments (0)