Create a new Array method in JavaScript?

Answered
yaboy01 asked this question 4 months ago
yaboy01 on Jan 20

In JavaScript, how do I apply a method directly to an array?

So I can use something like this:

array.doSomething()

And have it work on any array?

1 suggested answers
suparman21 on Jan 21

You can do it using Array.prototype:

Array.prototype.getFirstElement = function() {
  return this[0]
}

That creates a new getFirstElement() method you can apply to any array.

You would use it like this:

["123", "1245"].getFirstElement() // "123"
0 replies
Answered