snippet Friday 26 April 2024

Add a custom method to the JavaScript Array.prototype

Author

JavaScript comes with many methods that come standard on any array. It's part of its prototype. These methods include some things you have heard of such as .pop() or .push(). In all there about 20 of these. Each one has a specific functionality that makes arrays easier to work with. For instance .pop() removes an item from the end of an array and .push() adds an item to the end of an array.

Array.prototype.doStuff = function(){
  console.log('stuff happens')
}

var myArray = []

myArray.push('hello')

myArray.doStuff()