JavaScript Prototypes Explained prototype vs proto| Sabbirz | Blog

JavaScript Prototypes Explained prototype vs proto

js proto vs prototype

JavaScript Inheritance Guide to Prototypes and proto

Open your browser console. Type console.dir([]). Expand the array.

What do you see? A property called [[Prototype]] (or sometimes __proto__). ๐Ÿง

If youโ€™ve ever stared at that and wondered, "What on earth is the difference between prototype and __proto__?"โ€”you are not alone. It is one of the most confusing concepts in JavaScript, yet it is the backbone of how the entire language works.

Letโ€™s break it down like an expert. ๐Ÿ”จ

To understand this, we need to separate two distinct concepts:

  1. The Blueprint (prototype): This belongs to functions (specifically, constructor functions).
  2. The Link (__proto__): This belongs to objects (instances).

1. prototype: The Blueprint ๐Ÿ“

In JavaScript, functions are objects. When you create a function, JavaScript automatically gives it a special property called prototype.

Think of this as a Blueprint Box. Itโ€™s where you put methods and properties that you want future instances to inherit.

function Robot(name) {
  this.name = name;
}

// Adding a method to the Blueprint
Robot.prototype.speak = function() {
  console.log("Beep Boop ๐Ÿค–");
};

Here, Robot.prototype is the object that will become the parent of any new robot we create.

Now, letโ€™s create an instance:

const myBot = new Robot("R2-D2");

When myBot is born, JavaScript secretly links it to its parent's blueprint. This secret link is exposed in many browsers as __proto__.

console.log(myBot.__proto__ === Robot.prototype); // true โœ…

In simple terms:

  • Robot.prototype is the parent's stash of skills.
  • myBot.__proto__ is the child's wire connecting to that stash.

Why Do We See Both in the Console? ๐Ÿ–ฅ๏ธ

When you inspect an object in Chrome or Firefox, you are looking at the instance.

  • You see [[Prototype]] (or __proto__) because the browser is showing you who created this object.
  • Itโ€™s saying: "Hey, if you call a method I don't have, I'm going to look inside THIS object (my parent) to find it."

This chain of links is what we call the Prototype Chain. โ›“๏ธ

The "Official" Way ๐Ÿง

While __proto__ is widely supported, it was originally a non-standard feature. The "proper" modern way to access an object's prototype is:

Object.getPrototypeOf(myBot);

But letโ€™s be realโ€”we all still peek at __proto__ in the console for debugging. ๐Ÿ˜‰

Summary: The Cheat Sheet ๐Ÿ“„

Property Who has it? What does it do?
prototype Functions (Constructors) It's the Blueprint. It defines what instances will look like.
__proto__ Objects (Instances) It's the Link. It points back to the blueprint that created the object.

Deep Dive Resources ๐Ÿ“š

Want to master the depths of JavaScript? Check out these industry-standard resources:


Now go forth and debug that console with confidence! ๐Ÿš€

Related posts