February 18, 2014

As seen in A Re-Introduction To JavaScript

JavaScript functions are objects. So, when we declare a function, we get a bunch of other stuff for free! Take, the apply() method, which lets us pass an array into the arguments list of a method! I explain:

Say we have a function that calculates averages from a list of numbers passed into it:

function getAverage() { total = 0; for (i in arguments) { total += arguments[i]; } return total / arguments.length; }

We can now call this method to get the average of one or more numbers. Calling:

`getAverage(4,2,3,5);`

returns 3.5

We can also:

`getAverage.apply(null, [4,2,3,5]);`

which also returns 3.5!

Also, goes to show that functions are indeed Objects!