Tuesday, October 12, 2010

Array.prototype.slice.call(arguments)

The Array.prototype.slice.call() function is used to "coerce" JavaScript arguments (which are not really arrays) into JavaScript arrays..

I've seen examples such as:

[].slice.call(arguments, 1);

http://www.danwebb.net/2006/11/7/a-low-down-dirty-goblin-of-a-hack

The '1' argument means to slice the arguments list from 1 to the end.

The criticism about this approach is that [] creates a new Array object in memory. It is therefore more preferable to do:

Array.prototype.slice.call(arguments, 1);

Remember that all functions have a call and apply method(). So we're invoking the slice method by using call() in this case:
http://ryanmorr.com/archives/scope-context-in-javascript

call and apply

If you want to know how all the mainstream libraries do it, well it’s simple; call and apply. These two very simple methods inherent to all functions allow you to execute any function in any desired context. Before I continue, it is important to know that everything in JavaScript inherently has its own context, including DOM nodes, objects, arrays, strings, functions, etc. Meaning, any function can be executed in the context of any object using call and apply. This may seem insignificant, but understand it is this implementation that serves as an underlying bridge between the object-oriented and functional methodologies in the JavaScript language.

Making the Array-like Objects become Arrays

Well, that heading is a misnomer. If we want those array-like objects to behave like arrays, we are going to need a new array.

view plaincopy to clipboardprint?
var testFunction = function() {  
  // Create a new array from the contents of arguments  
  var args = Array.prototype.slice.call(arguments);  
  
  var a = args.shift();  
  console.log("The first argument is: %s", a);  
  
  // send the remaining arguments to some other function  
  someOtherFunction(args);  
};  
Clearly, the magic is all in Array.prototype.slice.call(arguments). So let me break it down per piece.

Array - this is the name of the base object that we want
prototype -this can be thought of as the namespace for the instance methods of an array
slice - this extracts a section of an array and returns a new array, and without a beginning and ending index, it simply returns a copy of the array
call - this is a very useful function, it allows you to call a function from one object and use it in the context of another

3 comments:

  1. You are the only person I've found online who was willing (able?) to tell me what the ",1" was in this statement: Array.prototype.slice.call(arguments, 1);

    Thank you and well done.

    ReplyDelete
  2. Thanks for this post, great explanation

    ReplyDelete