JavaScript: Array splice() with examples
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:
Let's look at the following examples to better understand how array.splice()
works.
- It can be used for deleting items from an array:
- It can be used for removing items from an array and inserting new ones:
- It can be used for truncating an array:
- It can be used for copying an array:
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#
- MDN - Array.splice()