JavaScript – Make Custom Functions with Prototype

In the current article, I will show you how to build functions for built-in objects in JavaScript. The way I know is using a prototype. Thus, I will create functions, giving us the last n values of an array or returning a capitalization of our string. It is useful and may save you some time.

JS

The functions come one by one. With some explanations.


  • string.Capitalize()

This one is just one line of code. The idea is to return the string with the first letter capitalized. The built-in function toUpperCase() does the whole work:


  • string.isBlank()

Not a science fiction again. It is a boolean function, telling us whether we have spaces before or after the string. It could be optimized, by using two returns and thus avoiding the if/else, but as far as it works OK, I will leave it as it is:


  • string.words()

This function returns a list of the string values, separated by one or more spaces. RegEx is used:


  • string.format()

This is indeed a valuable function. It does something, that is granted in languages such as C#. Anyway, now we have it in JavaScript as well:


  • array.head() and array.tail()

These two functions return the first or the last element of an array. Also available in C#, now in JS 🙂


  • array.range()

Ever dreamt to build an array of numbers with a small function? Now it is available in JS:


  • array.sum()

Summing an array in JS is as easy as in Python now. Enjoy it:


  • array.product()

Multiplication of an array is not an issue any more:


  • array.compact()

This function simply clears away your array from all values, which are going to return false – e.g.[false, 0, ,null,undefined, NaN]. The array myForbidden is not used, it stays there as a reminder:


  • array.take() and array.drop():

Taking the first N or the last N values of an array has never been easier in JS:


  • array.dedup()

Do you remember the set() in Python? Now we have something similar to it in JS:


  • array.sample()

Simply showing a random value from the array. Nothing more:


That’s all folks! The whole code is available in my GitHub repo here. Enjoy it!

About

VBA Developer