Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
  1. Code
  2. Web Development

Quick Tip: How to Extend Built-in Objects in JavaScript


Constructor functions, like Array, offer a wide range of methods and properties that you can make use of. But have ever wished that one of these objects offered some method that isn't built-in? Is there a way to do so yourself? Absolutely! Let's see how.

Reversing a String

This little snippet takes advantage of the Array object's "reverse" method, and applies its functionality to a given string. In effect, something like "hello" will be turned into "olleh," and can be accessed by using "myString.reverse()".

Bonus Question

Now that we have a basic of understanding of augmenting objects, can you figure out a way to write a custom "contains" method for the String object? For example, the jQuery library allows us to write things like:

The snippet above will search through all of the divs on the page, and then filter that wrapped set down to only those that contain the string "John." How could we extend the String object, with raw JavaScript, to allow for this? Leave your solution in the comments, and we'll discuss!

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.