JavaScript: check if function parameter is a string or an object

Functions can be made less strict (more human) by not limiting the parameter input to a certain data type.

If a function takes a DOM element as a parameter, it can be a string, or a jQuery object, for example. Or why not both? With a small conditional check it’s possible.

Take the following example, where the function simply gets element’s dimensions and returns and object:

var getElementDImensions = function(el) {
    var $el = $(el);
    return {
        width: $el.width(),
        height: $el.height()
    }
};

It expects the only parameter to be a string. But wouldn’t it be nice if it could be a jQuery object also? Turns out it’s pretty easy to do:

if (typeof myVar == 'string' || myVar instanceof String) {
    // Sting
} else {
    // Not a string. Since the function only takes
    // a string or an object, this level of checking
    // should be sufficient
}

This is exactly what ternary conditional statements are made for, the function in it’s final form:

/**
 * Gets element height and width as an array
 * @param  {mixed}  elem jQuery object or a string
 * @return {object}      Object with two nodes, width, and height
 */
var getElementDImensions = function(el) {
    // Check if parameter is string or object
    var $el = (typeof el == 'string' || el instanceof String) ? $(el) : el;
    return {
        width: $el.width(),
        height: $el.height()
    }
};

Usage example:

// Give it a jQuery object
var $el = $('#some-element'),
    dim = getElementDImensions($el);

// Or just a string
var dim = getElementDImensions('.some-element');

// Either way, `dim` now has width and height
console.log(dim.width);
console.log(dim.height);

Club-Mate, the beverage → club-mate.fi