JavaScript array methods splice and slice

javascript
Back

splice

To access part of an array without modifying it, see slice().

Syntax

splice(start);
splice(start, deleteCount);
splice(start, deleteCount, item1);
splice(start, deleteCount, item1, item2, itemN);

Examples

const months = ["Jan", "March", "April", "June"];
months.splice(1, 0, "Feb");
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]
// Now months become ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, "May");
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

For more details see splice on mdn.

slice

Syntax

slice();
slice(start);
slice(start, end);

Examples

const animals = ["ant", "bison", "camel", "duck", "elephant"];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

Parsing Array-like objects

function list() {
return Array.prototype.slice.call(arguments);
}
let list1 = list(1, 2, 3); // [1, 2, 3]

For more details see slice on mdn.

Thanks.

MIT © Mohan Dere.
-