Explanation of [].slice.call in javascript?

Yansky picture Yansky · Jan 24, 2010 · Viewed 76.2k times · Source

I stumbled onto this neat shortcut for converting a DOM NodeList into a regular array, but I must admit, I don't completely understand how it works:

[].slice.call(document.querySelectorAll('a'), 0)

So it starts with an empty array [], then slice is used to convert the result of call to a new array yeah?

The bit I don't understand is the call. How does that convert document.querySelectorAll('a') from a NodeList to a regular array?

Answer

Max Shawabkeh picture Max Shawabkeh · Jan 24, 2010

What's happening here is that you call slice() as if it was a function of NodeList using call(). What slice() does in this case is create an empty array, then iterate through the object it's running on (originally an array, now a NodeList) and keep appending the elements of that object to the empty array it created, which is eventually returned. Here's an article on this.

EDIT:

So it starts with an empty array [], then slice is used to convert the result of call to a new array yeah?

That's not right. [].slice returns a function object. A function object has a function call() which calls the function assigning the first parameter of the call() to this; in other words, making the function think that it's being called from the parameter (the NodeList returned by document.querySelectorAll('a')) rather than from an array.