7 days of WordPress plugins, themes & templates - for free!* Unlimited asset downloads! Start 7-Day Free Trial
  1. Code
  2. Web Development

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

Read Time: 1 min

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!

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Scroll to top
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.