Why ‘slice’ my arguments?: the jazz behind array.prototype.slice()

The commonly accepted way to convert a function’s arguments into a true array is by calling the JavaScript’s array slice method: Array.prototype.slice.call(arguments);

But my mom always taught me to look before I slice.  So I started wondering — Why do I call the ‘slice’ method, even though I’m not cutting anything shorter?

Research to the rescue!  First — the JavaScript source code (ECMAScript 5.1 currently) explains that the slice method is specially designed not only for taking snippets out of arrays, but for accepting various types of input — a single array, object, or array-like input — and returning an array.  Slice has the new Array() code built in, so returns an array no matter what kind of input it receives.

Next, I looked into the syntax.  Why would I put ‘arguments’ into the first slot instead of a start index?  

As it turns out, using the ‘call’ method provides ‘slice’ with an optional first argument — often referred to as the binding argument — which binds all instances of ‘this’ in the slice method to that first element (arguments) rather than to the context in which the slice is called.  If you understand how ‘this’ works in JavaScript, you know why that’s a significant step.

What about indices?  Shouldn’t I have to put indices for the slice, eg. Array.prototype.slice.call(arguments, 0, arguments.length)?

From the ECMAScript source: If no starting index is entered, slice is instructed to start at index 0.  If no ending index is entered, slice is instructed use this.length as the default.  So you’re basically taking a snippet — in this case, the entire arguments set — and calling new Array() on it.

Advertisements

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s