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
Clear
  1. It can be used for removing items from an array and inserting new ones:
Run
Clear
  1. It can be used for truncating an array:
Run
Clear
Run
Clear
  1. It can be used for copying an array:
Run
Clear

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 |