JS: Array.prototype.slice

By Xah Lee. Date: . Last updated: .

The “slice” function lets you extract a sub-array from a array.

Return a array, from index start to to end but does not include end.

start default to 0.

end default to length of myArray.

start and end can be negative. When negative, count begin from last element.

Original array is not modified.

// take a sub list, starting with index 1

const r1 = [3,4,2];
const r2 = r1.slice(1);

console.log(r1); // [3,4,2]
console.log(r2); // [4,2]
// extract a sub array, from index 1 to 2 (excludes element at index 2)

const r1 = ["a","b","c","d"];
const r2 = r1.slice(1,2);

console.log(r1); // ["a","b","c","d"]
console.log(r2); // ["b"]
// Array.prototype.slice can be used on array-like object to convert it to array

const r1 = {"0":"a", "1":"b", "length":2};
const r2 = Array.prototype.slice.call(r1,0,3);

console.log(r1); // { '0': 'a', '1': 'b', length: 2 }
console.log(r2); // [ 'a', 'b' ]

[see JS: Array-Like Object to Array]


ECMAScript® 2016 Language Specification#sec-array.prototype.slice

Array Topic

  1. JS: Array Basics
  2. JS: Understand JS Array
  3. JS: Create Array
  4. JS: Sparse Array
  5. JS: Array-Like Object
  6. JS: Array How-To
  7. JS: Array Object
  8. JS: Array.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.