Array.prototype.slice()

  • Revision slug: Web/JavaScript/Reference/Global_Objects/Array/slice
  • Revision title: Array slice method
  • Revision id: 450357
  • Created:
  • Creator: Brettz9
  • Is current revision? No
  • Comment

Revision Content

Summary

Returns a shallow copy of a portion of an array.

Method of Array
Implemented in JavaScript 1.2
ECMAScript Edition ECMAScript 3rd Edition

Syntax

Array.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 second-to-last element and the last element in the sequence.
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 String and 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.

Examples

Example: Return a portion of an existing array

// Our good friend the citrus from fruits example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);

// puts --> ["Orange","Lemon"]

Example: Using slice

In the following example, slice creates a new array, newCar, from myCar. Both include a reference to the object myHonda. When the color of myHonda is changed to purple, both arrays reflect the change.

// Using slice, create newCar from myCar.
var myHonda = { color: "red", wheels: 4, engine: { cylinders: 4, size: 2.2 } };
var myCar = [myHonda, 2, "cherry condition", "purchased 1997"];
var newCar = myCar.slice(0, 2);

// Display the values of myCar, newCar, and the color of myHonda
//  referenced from both arrays.
console.log("myCar = " + myCar.toSource());
console.log("newCar = " + newCar.toSource());
console.log("myCar[0].color = " + myCar[0].color);
console.log("newCar[0].color = " + newCar[0].color);

// Change the color of myHonda.
myHonda.color = "purple";
console.log("The new color of my Honda is " + myHonda.color);

// Display the color of myHonda referenced from both arrays.
console.log("myCar[0].color = " + myCar[0].color);
console.log("newCar[0].color = " + newCar[0].color);

This script writes:

myCar = [{color:"red", wheels:4, engine:{cylinders:4, size:2.2}}, 2, "cherry condition", "purchased 1997"]
newCar = [{color:"red", wheels:4, engine:{cylinders:4, size:2.2}}, 2]
myCar[0].color = red 
newCar[0].color = red
The new color of my Honda is purple
myCar[0].color = purple
newCar[0].color = purple

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'.

function list() {
  return Array.prototype.slice.call(arguments, 0);
}

var list1 = list(1, 2, 3); // [1, 2, 3]

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.

var unboundSlice = Array.prototype.slice;
var slice = Function.prototype.call.bind(unboundSlice);

function list() {
  return slice(arguments, 0);
}

var list1 = list(1, 2, 3); // [1, 2, 3]

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.)

/**
 * Shim for "fixing" IE's lack of support (IE < 9) for applying slice
 * on host objects like NamedNodeMap, NodeList, and HTMLCollection
 * (technically, since host objects have been implementation-dependent (at least before ES6),
 * IE hasn't need to work this way). Also works on strings,
 * fixes IE < 9 to allow an explicit undefined for the 2nd argument
 * (as in Firefox), and prevents errors when called on other
 * DOM objects.
*/
(function () {
    'use strict';
    var _slice = Array.prototype.slice;

    try {
        _slice.call(document.documentElement); // Can't be used with DOM elements in IE < 9
    }
    catch (e) { // Fails in IE < 9
        Array.prototype.slice = function (begin, end) {
            var i, arrl = this.length, a = [];
            if (this.charAt) { // Although IE < 9 does not fail when applying Array.prototype.slice
                               // to strings, here we do have to duck-type to avoid failing
                               // with IE < 9's lack of support for string indexes
                for (i = 0; i < arrl; i++) {
                    a.push(this.charAt(i));
                }
            }
            else { // This will work for genuine arrays, array-like objects, NamedNodeMap (attributes, entities, notations), NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes), and will not fail on other DOM objects (as do DOM elements in IE < 9)
                for (i = 0; i < this.length; i++) { // IE < 9 (at least IE < 9 mode in IE 10) does not work with node.attributes (NamedNodeMap) without a dynamically checked length here
                    a.push(this[i]);
                }
            }
            return _slice.call(a, begin, end || a.length); // IE < 9 gives errors here if end is allowed as undefined (as opposed to just missing) so we default ourselves
        };
    }
}());

 

See also

Revision Source

<h2 id="Summary" name="Summary">Summary</h2>
<p>Returns a shallow copy of a portion of an array.</p>
<table class="standard-table">
  <thead>
    <tr>
      <th class="header" colspan="2">Method of <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="JavaScript/Reference/Global_Objects/Array"><code>Array</code></a></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>Implemented in</th>
      <td>JavaScript 1.2</td>
    </tr>
    <tr>
      <th>ECMAScript Edition</th>
      <td>ECMAScript 3rd Edition</td>
    </tr>
  </tbody>
</table>
<h2 id="Syntax" name="Syntax">Syntax</h2>
<pre class="syntaxbox">
<code><var>Array</var>.slice(<em>begin</em>[, <em>end</em>])</code></pre>
<h2 id="Parameters" name="Parameters">Parameters</h2>
<dl>
  <dt>
    <code>begin</code></dt>
  <dd>
    Zero-based index at which to begin extraction.</dd>
  <dd>
    As a negative index, <code>begin</code> indicates an offset from the end of the sequence. <code>slice(-2)</code> extracts the second-to-last element and the last element in the sequence.</dd>
</dl>
<dl>
  <dt>
    <code>end</code></dt>
  <dd>
    Zero-based index at which to end extraction. <code>slice</code> extracts up to but not including <code>end</code>.</dd>
  <dd>
    <code>slice(1,4)</code> extracts the second element through the fourth element (elements indexed 1, 2, and 3).</dd>
  <dd>
    As a negative index, <code>end</code> indicates an offset from the end of the sequence. <code>slice(2,-1)</code> extracts the third element through the second-to-last element in the sequence.</dd>
  <dd>
    If <code>end</code> is omitted, <code>slice</code> extracts to the end of the sequence.</dd>
</dl>
<h2 id="Description" name="Description">Description</h2>
<p><code>slice</code> 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:</p>
<ul>
  <li>For object references (and not the actual object), <code>slice</code> 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.</li>
</ul>
<ul>
  <li>For strings and numbers (not <a href="/en-US/docs/JavaScript/Reference/Global_Objects/String" title="JavaScript/Reference/Global_Objects/String">String</a> and <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Number" title="JavaScript/Reference/Global_Objects/Number">Number</a> objects), <code>slice</code> copies strings and numbers into the new array. Changes to the string or number in one array does not affect the other array.</li>
</ul>
<p>If a new element is added to either array, the other array is not affected.</p>
<h2 id="Examples" name="Examples">Examples</h2>
<h3 id="Example:_Return_a_portion_of_an_existing_array" name="Example:_Return_a_portion_of_an_existing_array">Example: Return a portion of an existing array</h3>
<pre class="brush: js">
// Our good friend the citrus from fruits example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);

// puts --&gt; ["Orange","Lemon"]</pre>
<h3 id="Example:_Using_slice" name="Example:_Using_slice">Example: Using <code>slice</code></h3>
<p>In the following example, <code>slice</code> creates a new array, <code>newCar</code>, from <code>myCar</code>. Both include a reference to the object <code>myHonda</code>. When the color of <code>myHonda</code> is changed to purple, both arrays reflect the change.</p>
<pre class="brush: js">
// Using slice, create newCar from myCar.
var myHonda = { color: "red", wheels: 4, engine: { cylinders: 4, size: 2.2 } };
var myCar = [myHonda, 2, "cherry condition", "purchased 1997"];
var newCar = myCar.slice(0, 2);

// Display the values of myCar, newCar, and the color of myHonda
//  referenced from both arrays.
console.log("myCar = " + myCar.toSource());
console.log("newCar = " + newCar.toSource());
console.log("myCar[0].color = " + myCar[0].color);
console.log("newCar[0].color = " + newCar[0].color);

// Change the color of myHonda.
myHonda.color = "purple";
console.log("The new color of my Honda is " + myHonda.color);

// Display the color of myHonda referenced from both arrays.
console.log("myCar[0].color = " + myCar[0].color);
console.log("newCar[0].color = " + newCar[0].color);
</pre>
<p>This script writes:</p>
<pre class="brush: js">
myCar = [{color:"red", wheels:4, engine:{cylinders:4, size:2.2}}, 2, "cherry condition", "purchased 1997"]
newCar = [{color:"red", wheels:4, engine:{cylinders:4, size:2.2}}, 2]
myCar[0].color = red 
newCar[0].color = red
The new color of my Honda is purple
myCar[0].color = purple
newCar[0].color = purple
</pre>
<h2 id="Array-like" name="Array-like">Array-like objects</h2>
<p><code>slice</code> method can also be called to convert Array-like objects / collections to a new Array. You just bind the method to the object. The <code>arguments</code> inside a function is an example of an 'array-like object'.</p>
<pre class="brush: js">
function list() {
  return Array.prototype.slice.call(arguments, 0);
}

var list1 = list(1, 2, 3); // [1, 2, 3]
</pre>
<p>Binding can be done with the .<code>call</code> function of <code>Function.prototype</code> and it can also be reduced using <code>[].slice.call(arguments)</code> instead of <code>Array.prototype.slice.call</code>. Anyway, it can be simplified using <code>bind</code>.</p>
<pre class="brush: js">
var unboundSlice = Array.prototype.slice;
var slice = Function.prototype.call.bind(unboundSlice);

function list() {
  return slice(arguments, 0);
}

var list1 = list(1, 2, 3); // [1, 2, 3]
</pre>
<h2 id="Streamlining_cross-browser_behavior">Streamlining cross-browser behavior</h2>
<p>Although host objects (such as DOM objects) are not required by spec to follow the Mozilla behavior when converted by <code>Array.prototype.slice</code> and IE &lt; 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 <em>de facto</em> standard behavior. (The shim also fixes IE to work with the second argument of <code>slice()</code> being an explicit <code>null</code>/<code>undefined</code> value as earlier versions of IE also did not allow but all modern browsers, including IE &gt;= 9, now do.)</p>
<pre class="brush: js">
/**
&nbsp;* Shim for "fixing" IE's lack of support (IE &lt; 9) for applying slice
&nbsp;* on host objects like NamedNodeMap, NodeList, and HTMLCollection
&nbsp;* (technically, since host objects have been implementation-dependent (at least before ES6),
&nbsp;* IE hasn't need to work this way). Also works on strings,
&nbsp;* fixes IE &lt; 9 to allow an explicit undefined for the 2nd argument
&nbsp;* (as in Firefox), and prevents errors when called on other
&nbsp;* DOM objects.
*/
(function () {
&nbsp;&nbsp;&nbsp; 'use strict';
&nbsp;&nbsp;&nbsp; var _slice = Array.prototype.slice;

&nbsp;&nbsp;&nbsp; try {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _slice.call(document.documentElement); // Can't be used with DOM elements in IE &lt; 9
&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; catch (e) { // Fails in IE &lt; 9
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Array.prototype.slice = function (begin, end) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var i, arrl = this.length, a = [];
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (this.charAt) { // Although IE &lt; 9 does not fail when applying Array.prototype.slice
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // to strings, here we do have to duck-type to avoid failing
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // with IE &lt; 9's lack of support for string indexes
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (i = 0; i &lt; arrl; i++) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; a.push(this.charAt(i));
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else { // This will work for genuine arrays, array-like objects, NamedNodeMap (attributes, entities, notations), NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes), and will not fail on other DOM objects (as do DOM elements in IE &lt; 9)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (i = 0; i &lt; this.length; i++) { // IE &lt; 9 (at least IE &lt; 9 mode in IE 10) does not work with node.attributes (NamedNodeMap) without a dynamically checked length here
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; a.push(this[i]);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return _slice.call(a, begin, end || a.length); // IE &lt; 9 gives errors here if end is allowed as undefined (as opposed to just missing) so we default ourselves
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; };
&nbsp;&nbsp;&nbsp; }
}());

</pre>
<p>&nbsp;</p>
<h2 id="See_also">See also</h2>
<ul>
  <li><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/call" rel="internal" title="JavaScript/Reference/Global_Objects/Function/call">Function.prototype.call</a></code></li>
  <li><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind" rel="internal" title="JavaScript/Reference/Global_Objects/Function/bind">Function.prototype.bind</a></code></li>
</ul>
Revert to this revision