SidekickJS's blog

A few uses for apply()

apply() is most often used for building higher-order functions, but it has uses in normal, straight line coding with Javascript too.

I very commonly use apply() to make a var-args function more useful. Math.max and Math.min are frequent targets. Let’s say we want to find the minimum age of our users:

var minAge = Math.min.apply(null,userAges)

We can generalise this to a Math.arrayMin, and arrayMax, rather than cofusing later readers of our code:

Math.arrayMin = function(array) {
  return Math.min.apply(null,array)
}

Another example might be joining a variable number of arrays together. If we have an array of arrays, we can:

var variableNumberOfArrays = [[1,2,3],[4,5,6]]
[].concat.apply([],variableNumberOfArrays) // [1,2,3,4,5,6]

In case you’re wondering, this isn’t the same as flattening, we’re just performing a concatenation. So [[[1],2,3],[4,5,6]] would come out [[1],2,3,4,5,6].

Again it’s probably best to name an intention revealing function rather than scattering the slightly confusing idiom all over the place:

Array.prototype.concatArrays = function(arrays) {
  return this.concat.apply(this,arrays)
}

So if you’re faced with a function taking a variable number of arguments, and wished you could pass an array: you can. Another job for Function.prototype.apply()!

I’ll be sharing more JS tools and tricks, follow me to hear about them!