DEV Community

Cover image for JavaScript Proto and Prototype ⚙️
Maxine
Maxine

Posted on • Updated on

JavaScript Proto and Prototype ⚙️

Table Of Contents

Introduction

Javascript can be described as a prototype-based language. This stems from an object's ability to have a prototype object, which allows them to inherit features from one another. You can read more about this in the MDN Web Docs.

But if you've ever looked at an arrary in your console, you may notice __proto__, what exactly is that?

What is Proto?

If you don't already, open up your browser console. Now, create an empty array ([]). After you create the array, expand it using the > icon. Viola! You will see the **proto** attribute.

[]
length: 0
__proto__: Array(0) // <--- Here it is!
length: 0
constructor: ƒ Array()
concat: ƒ concat()
Enter fullscreen mode Exit fullscreen mode

It does not matter how you create your array, you'll always find the proto attribute.

let example = [1,2,3,4,5]

example
(5) [1, 2, 3, 4, 5]
0: 1
1: 2
2: 3
3: 4
4: 5
length: 5
__proto__: Array(0) <-- woah! There it is again!
Enter fullscreen mode Exit fullscreen mode

Every time we construct a new array, it uses the Array constrcutor, so proto looks for an array blueprint. It references all properties and methods from that blueprint. If you type Array.prototype, you'll see same method list as the one above.

Proto is Javascript's way to reference to the original prototype. And this applies to any react object!

Let's try out another example...

Object.prototype

{constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}
Enter fullscreen mode Exit fullscreen mode

Boom! All the methods and properties.

Adding to prototype

Believe it or not, you can actually add your own methods to the Array blueprint.

Array.prototype.phrase = () => console.log("I like math")
Enter fullscreen mode Exit fullscreen mode

Now any existing array will have this phrase method, including the example array we just created:

(5) [1, 2, 3, 4, 5]
0: 1
1: 2
2: 3
3: 4
4: 5
length: 5
__proto__: Array(0)
phrase: () => console.log("I like math") <--- Magic.
Enter fullscreen mode Exit fullscreen mode

If you were to call the phrase method...

example.phrase() // "I love math"
Enter fullscreen mode Exit fullscreen mode

Conclusion

  1. Everything in javascript references methods/properties from its blueprint.
  2. You can add and modify prototype features in the blueprint.
  3. Proto references the original blueprint's prototype features.

While there is more to dig into, this covers the basics of Javascript prototype and what it has to offer. Thanks for reading!

Top comments (0)