Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the use of Array.prototype.slice.call(array, 0)?

I was just browsing Sizzle's source code and I came across this line of code:

array = Array.prototype.slice.call( array, 0 ); 

I looked up what the function is, but I came to the conclusion that it just returns all elements of the array starting from index 0, and puts the whole into the array, i.e. it doesn't really do anything at all.

What is therefore the use of this line of code? What am I missing?

Edit: It's line 863 from https://github.com/jquery/sizzle/blob/master/sizzle.js#L863.

like image 569
pimvdb Avatar asked Feb 28 '11 17:02

pimvdb


People also ask

What is the use of array slice function?

JavaScript Array slice() The slice() method returns selected elements in an array, as a new array. The slice() method selects from a given start, up to a (not inclusive) given end. The slice() method does not change the original array.

Why array prototype is an array?

In the specs, the reason is said to be: The Function prototype object is specified to be a function object to ensure compatibility with ECMAScript code that was created prior to the ECMAScript 2015 specification. (this also applies to arrays) That's the why.


2 Answers

The DOM usually returns a NodeList for most operations like getElementsByTagName.

Although a NodeList almost feels like an array, it is not. It has a length property like an array does, and a method item(index) to access an object at the given index (also accessible with the [index] notation), but that's where the similarity ends.

So to be able to use the wonderful array methods without rewriting them all for a NodeList, the above line is useful.

Another use of converting it to an array is to make the list static. NodeLists are usually live, meaning that if document changes occur, the NodeList object is automatically updated. That could cause problems, if a jQuery object returned to you kept changing right under your nose. Try the following snippet to test the liveness of NodeLists.

var p = document.getElementsByTagName('p'); console.log(p.length); // 2 document.body.appendChild(document.createElement('p')); // length of p changes as document was modified console.log(p.length); // 3 
like image 52
Anurag Avatar answered Oct 18 '22 04:10

Anurag


What's happening here is that Sizzle is creating an actual array out of an array-like object. The array-like object doesn't necessarily have the slice() method, so the prototype method has to be called directly. makeArray() returns a copy of that array-like object that is an actual array, and can be used as such else where.

See here for more information about array-like objects.

like image 21
James Sulak Avatar answered Oct 18 '22 04:10

James Sulak