Recently, I was working on some coding katas and encountered a problem that asked me to add a new method to an array. This got me curious about JavaScript prototypes and how they can be used to add custom methods to objects like arrays.
JavaScript Object Prototypes
Prototypes are the mechanism by which JavaScript objects inherit features from one another. In this article, we explain what a prototype is, how prototype chains work, and how a prototype for an object can be set.
Basically in a nutshell, all objects in JavaScript (and most things are objects in JavaScript 😂) and there is a built-in property called a prototype
.
When an object is created, it inherits from a built-in object called Object.prototype, which provides some basic methods like toString() and valueOf().
Confusing but funny fact: The Prototype property itself is an object too — so it will have it’s own prototype
Using Prototypes to add methods to Arrays
So back to my coding Kata’s — you can easily add methods onto existing ‘objects’ like Arrays (yes in JavaScript Arrays are objects too! 😎)
For example, let’s say we want to add a method called first()
to arrays, which returns the first element of the array.
Here’s how we can define the getFirst()
method using prototypes:
// Example. add a new 'first' method onto Arrays.
// This method will return the first item in the array.
Array.prototype.getFirst = function() {
if (this.length < 1) {
return -1
}
return this[0]
}
This code adds a new method called first()
to the Array prototype. The this
keyword refers to the array that the method is called on, so this[0]
returns the first element of the array.
Now, we can use the first()
method on any array:
const myArray = [1, 2, 3, 4, 5];
console.log(myArray.getFirst()); // 1
By using prototypes to add custom methods to arrays, we can extend the functionality of arrays and make our code more flexible and reusable.
Conclusion
In this quick blog, we’ve explored JavaScript prototypes and how they can be used to add custom methods to objects like arrays. By understanding prototypes, we can extend the functionality of existing objects and create more flexible and reusable code. For more information on prototypes and JavaScript objects, check out the MDN documentation and w3schools on the topic.