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

mVChr picture mVChr · Feb 17, 2011 · Viewed 36.6k times · Source

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?

Answer

Anon. picture Anon. · Feb 17, 2011

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.