I am Hack Sparrow
Captain of the Internets.

JavaScript Array Splice – Syntax and Examples

The Splice Method of JavaScript with Examples

The JavaScript splice method is a multi-purpose tool. The syntax of the Array method is as follows.

Array.splice(startIndex[, endIndex, [item1[, item2, item3, ...]]])

The following examples demonstrate the way the splice method can be used.

The JavaScript splice method can be used for removing items from an array.

var a = ['apple', 'donkey', 'dog', 'mango', 'orange'];
a.splice(1, 2);
console.log(a);
// ['apple', 'mango', 'orange']

The JavaScript splice method can be used for removing items from an array and inserting new ones.

var a = ['apple', 'donkey', 'dog', 'mango', 'orange'];
a.splice(1, 2, 'plum', 'cherry', 'peach');
console.log(a);
// ['apple', 'plum', 'cherry', 'peach', 'mango', 'orange']

The JavaScript splice method can be used for truncating an array.

var a = ['apple', 'plum', 'cherry', 'peach', 'mango', 'orange'];
a.splice(3);
console.log(a);
// ['apple', 'plum', 'cherry']

Example 1

var a = ['apple', 'plum', 'cherry', 'peach', 'mango', 'orange'];
var b = a.splice(a.indexOf('cherry'));
console.log(a);
// ['apple', 'plum']
console.log(b);
// ['cherry', 'peach', 'mango', 'orange']

Example 2

The JavaScript splice method can be used for copying an array. Note, it will work as a proper copying tool only if the array items are primitive data types. If the array items are Objects, they will be passed by reference and not by value.

var a = ['apple', 'plum', 'cherry', 'peach', 'mango', 'orange'];
var b = a.splice(0);
console.log(a);
// []
console.log(b);
// ['apple', 'plum', 'cherry', 'peach', 'mango', 'orange']

Reference

One Response to “JavaScript Array Splice – Syntax and Examples”

  1. Russ Methlie says:

    The syntax you specified is incorrect. The second arg of splice is not the end index, but the count (i.e., the number of items to remove). Your examples still work, but only by accident. If you had used:

    a.splice( 0, 2 )

    you would not get the expected result.

    Array.splice() Reference

Make a Comment