Explanation of [].slice.call in javascript?

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.

Leave a Comment