Storing Metadata on Arrays in JavaScript

Originally published in the A Drip of JavaScript newsletter.

We've talked before about the fact that in JavaScript, even arrays are objects. But one thing we haven't really talked about is the sort of flexibility that this implies.

Suppose that we have a system which we can query for records, but we want to be able to capture the time at which those records were returned. We could do something like this:

var digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

function filterDigits (filterFn) {
    return {
        result: digits.filter(filterFn),
        timestamp: new Date()
    };
}

var filterObj = filterDigits(function(x) {
    return (x > 8);
});

// Outputs: [9]
console.log(filterObj.result);

// Outputs: Mon Nov 04 2013 13:34:09 GMT-0500 (EST)
console.log(filterObj.timestamp);

This works okay. But if you think about it, it is a little odd having to create an entirely new object just to store metadata. Wouldn't it be nice if you could just store that metadata directly on the the resulting array? It turns out that you can.

var digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

function filterDigits (filterFn) {
    var result = digits.filter(filterFn);
    result.timestamp = new Date();

    return result;
}

var filtered = filterDigits(function(x) {
    return (x > 8);
});

// Outputs: [9]
// Visual output may vary depending on your console.
console.log(filtered);

// Outputs: Mon Nov 04 2013 13:34:09 GMT-0500 (EST)
console.log(filtered.timestamp);

Because an array is an object, you can assign arbitrary properties to it. Using this approach means that our code maintains focus on the central concern (the results array) while still carrying around the metadata for those places which need it.

Looking at the changes in the variable names can help illuminate why it is an improvement. On the one hand, the name filterObj essentially means "a collection of disparate values." The name filtered on the other hand, conveys a single concept.

It's a little improvement, but little improvements add up over time.

Want to improve your JavaScript skills?
Subscribe to A Drip of JavaScript for biweekly tips to help you level up as a JS developer.