What's the point of .slice(0) here?

42,192

Solution 1

sort() modifies the array it's called on - and it isn't very nice to go around mutating stuff that other code might rely on.

slice() always returns a new array - the array returned by slice(0) is identical to the input, which basically means it's a cheap way to duplicate an array.

Solution 2

arr.slice(0) makes a copy of the original array by taking a slice from the element at index 0 to the last element.

It's also used to convert array-like objects into arrays. For example, a DOM NodeList (returned by several DOM methods like getElementsByTagName) is not an array, but it is an array-like object with a length field and is indexable in JavaScript. To convert it to an array, one often uses:

var anchorArray = [].slice.call(document.getElementsByTagName('a'), 0)

Solution 3

slice(0) creates a new array identical to the original array. Many times you want to preserve your original array and create a new one.

If you use slice(1), it will create a different array starting from index position 1.

Similar things hold for strings as well.

Solution 4

slice(0) allows you to return an array of the existing array you're referencing, in this case namespaces.

Share:
42,192

Related videos on Youtube

mVChr
Author by

mVChr

I prefer analog.

Updated on July 05, 2022

Comments

  • mVChr
    mVChr over 1 year

    I was studying the jQuery source when I found this (v1.5 line 2295):

    namespace = new RegExp("(^|\\.)" +
      jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
    

    My question is, why use slice(0) here?

  • Ribo
    Ribo over 12 years
    slice is 'undefined' for the value returned by document.getElementsByName (in Firefox 3.16). I used: var iiNodes=[], tmp = editorDocument.getElementsByName("intInfo"); for (var ii=0; ii<tmp.length; ii++) { iiNodes.push(tmp[ii]); } to get around the problem.
  • ide
    ide over 12 years
    HTMLCollection.slice is undefined but Array.slice does exist, hence the [].slice.call business.
  • Michael Laffargue
    Michael Laffargue almost 8 years
    @ide answer is more precise : "also used to convert array-like objects into arrays"
  • zfj3ub94rf576hc4eegm
    zfj3ub94rf576hc4eegm almost 6 years
    No, the result will be ["Lemon", "Apple"] to be precise. And we all know what slice() does. Stackoverflow isn't for regurgitating documentation. The question is about what the point of slice(0) is. Which in this context your question does not answer at all.
  • kchetan
    kchetan almost 4 years
    In an example I saw, const nav = Array.prototype.slice.call(document.querySelectorAll('.nav')‌​, 0); why is using Array.prototype better than []?

Related