Revision Content

Summary

The slice() method returns a shallow copy of a portion of an array into a new array object.

Syntax

arr.slice(begin[, end])

Parameters

begin

Zero-based index at which to begin extraction.

As a negative index, begin indicates an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence.

If begin is omitted, slice begins from index 0.

end

Zero-based index at which to end extraction. slice extracts up to but not including end.

slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3).

As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence.

If end is omitted, slice extracts to the end of the sequence.

Description

slice does not alter the original array, but returns a new "one level deep" copy that contains copies of the elements sliced from the original array. Elements of the original array are copied into the new array as follows:

For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

For strings and numbers (not {{jsxref("Global_Objects/String", "String")}} and {{jsxref("Global_Objects/Number", "Number")}} objects), slice copies strings and numbers into the new array. Changes to the string or number in one array does not affect the other array.

If a new element is added to either array, the other array is not affected.

Array-like objects

slice method can also be called to convert Array-like objects / collections to a new Array. You just bind the method to the object. The arguments inside a function is an example of an 'array-like object'.

Binding can be done with the .call function of Function.prototype and it can also be reduced using [].slice.call(arguments) instead of Array.prototype.slice.call. Anyway, it can be simplified using bind.

Streamlining cross-browser behavior

Although host objects (such as DOM objects) are not required by spec to follow the Mozilla behavior when converted by Array.prototype.slice and IE < 9 does not do so, versions of IE starting with version 9 do allow this, "shimming" it can allow reliable cross-browser behavior. As long as other modern browsers continue to support this ability, as currently do IE, Mozilla, Chrome, Safari, and Opera, developers reading (DOM-supporting) slice code relying on this shim will not be misled by the semantics; they can safely rely on the semantics to provide the now apparently de facto standard behavior. (The shim also fixes IE to work with the second argument of slice() being an explicit null/undefined value as earlier versions of IE also did not allow but all modern browsers, including IE >= 9, now do.)