Collection of small useful javascript functions

Collection of small useful javascript functions

Every once in a while I'll be working on some minor javascript stuff and need some little nifty function that is usually available through whatever javascript framework being used - be it lodash, jQuery, angular or something else - but I can't or don't want/need to use one of those.

In those situation I usually end up searching StackOverflow for the solution and most likely have to test a few of them to find the best and most modern version.

To help my self I've decided to save some of them for ease of access and future use, so here goes:

  • Pad left
  • Debounce

Pad left

This will add a character to the left of the input value until the total length of the value is the specified width.

This is useful for stuff like right-aligning text and padding numbers with leading zeros.

var padLeft = function (value, width, char) {
    char = (char !== undefined) ? char : " ";
    width = (typeof width === "number") ? width : parseInt(width);
    value = String(value);
    return Array(1 + width - value.length).join(char) + value;

This works with both strings and numbers for input. Please note that negative numbers is not handled correctly.


// Right-aligning text
padLeft("Blue", 10, " ")
padLeft("Orange", 10, " ")

// Result:
//      Blue
//    Orange
// Padding numbers with leading zeros
padLeft(5, 3, 0)
padLeft(42, 3, 0)
padLeft(137, 3, 0)

// Result:
// 005
// 042
// 137


Debouncing means waiting a set amount of time before executing a specified function.

This is useful in many different situations, for example an autosuggest feature where you only want to load suggestion after the user is done typing instead of continuously after each keypress.

// 'wait' is time in milliseconds
var debounce = function (func, wait) {
    var timeout;
    return function () {
        var context = this, args = arguments;
        timeout = setTimeout(function () {
            func.apply(context, args);
        }, wait || 0);


var loadSuggestions = function() {
    // Load suggestions from web service

// debounce(..) returns a new function.
// You have to save and reuse the returned function for it to work as expected.
var loadSuggestionsDebounce = debounce(loadSuggestions, 250);

var textfield = document.getElementById("textfield");
textfield.addEventListener("keypress", loadSuggestionsDebounce);