JavaScript array.splice() explained with examples#

.splice() is an instance method on all JavaScript arrays. Depending on the parameters you pass, it has a very multipurpose functionality. Here is what its syntax looks like:

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

Let's look at the following examples to better understand how array.splice() works.

  1. It can be used for deleting items from an array:

[run]

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

[/run]

  1. It can be used for removing items from an array and inserting new ones:

[run]

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

[/run]

  1. It can be used for truncating an array:

[run]

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

[/run]

[run]

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

[/run]

  1. It can be used for copying an array:

[run]

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

[/run]

array.splice() creates true copies of the items in an array only if the items are primitive data types (boolean, number, string, null, undefined, NaN). If the array items are Objects, they will be passed by reference and not by value, hence not copies but references.

References#

  1. MDN - Array.splice()
Tweet this | Share on LinkedIn |