27 January 2015

Splat operator VS arguments psuedo-array

Imagine this: You have a nested function and you want to access the arguments from an outter function from inside an inner function. The only way to achieve this using JavaScript's arguments psuedo-array would be to store the contents of arguments in a variable. Otherwise it would be inaccessible from an inner function, since when functions are nested, arguments refers to the formal parameters of the current function.

CoffeeScript's splat operator (...) allows custom naming of the variable we want to hold arguments. This means no more shadowing when using arguments psuedo-array with nested functions. Check out the splat operator in action:

Example:

_.compose = (functions...) ->
  (args...) ->
    _.each functions, (fn) ->
      args = [fn.apply(fn, args)]
    args[0]

Using splat operator's makes it easy to access arguments from different functions while maintaining readability.

Splat operator provides access to all array methods

Using the splat operator transforms the arguments psuedo-array into a real array. This is what the splat operator is doing under the hood in our above example:

functions = 1 <= arguments.length ? __slice.call(arguments, 0) : [];

The arguments pseudo-array has slice applied to it which copies over the format parameters into a real array. Using a real array instead of a pseudo-array provides the ability to use methods which would be inaccessible other.