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]

JS Array

  1. Understand JS Array
  2. Create Array
  3. Sparse Array
  4. Array-Like Object
  5. Array How-To
Liket it? I spend 2 years writing this tutorial. Help me spread it. Tell your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

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

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Object Reference
  5. DOM Scripting
  6. SVG
  7. Blog