Writing reusable JavaScript

Don’t reinvent the wheel, just realign it. — Anthony J. D’Angelo

It is the small things that count

Small problems are usually overlooked by the developer, I myself have rushed and wrote sloppy functions as I had lack of care for the smaller problem.

An example of rushing:

$("button").click(function(){
var heading = $("h1").text();
var capital = heading[0].toUpperCase() + heading.slice(1);
$("h1").text(capital);
});

How can we improve this? Right away we can pull out the entire function so it is no longer an anonymous function, this helps when we need to debug and allows us to reuse this block of code:

function capitalizeHeading() {
var heading = $("h1").text();
var capital = heading[0].toUpperCase() + heading.slice(1);
$("h1").text(capital);
}
$("button").click(capitalizeHeading);

Lets make this even more useful and extract the capitalizing logic:

function capitalize(word) {
return word[0].toUpperCase() + word.slice(1);
}
function capitalizeHeading() {
var heading = $("h1").text();
$("h1").text(capitalize(heading));
}
$("button").click(capitalizeHeading);

Now we can reuse the capitalizing logic across our program.

Did you know that jQuery constructs a new Object and queries the DOM every time you call $(<selector>)?. We should cache jQuery objects in order to speed up execution times:

function capitalize(word) {
return word[0].toUpperCase() + word.slice(1);
}
function capitalizeHeading() {
var $h1 = $("h1"); // cache h1 in a variable
$h1.text(capitalize($h1.text())); // reuse without creating
}
$("button").click(capitalizeHeading);

capitalizeHeading is okay for this one use case but it would be much more useful if it accepted a parameter to indicate what elements to capitalize:

function capitalize(word) {
return word[0].toUpperCase() + word.slice(1);
}
function capitalizeElement(element) {
var $el = $(element);
$el.text(capitalize($el.text()));
}
$("button").click(capitalizeElement.bind(capitalizeElement, "h1"));

We can use bind in order to create a partial function. This is a function which has its arguments preloaded before execution, in this case we have made the element parameter a “h1”.

Bind in action

Turning capitalizeHeading into capitalizeElement(<element>) allows us to reuse that function for any element we wish to capitalize:

capitalizeElement("h2");
capitalizeElement("div[data-title]");

We have split the original callback into 2 reusable functions. By doing so we have begun to follow the DRY (Don’t Repeat Yourself) principle.

If you have any questions regarding this article, you can find me on Instagram: kameron_tanseli