In javascript, we use two methods slice() and splice() very often, but still, get confused between them. Here you can have a quick look at these methods and find the difference.
1. Uses.
slice()
: This method is used to select array elements.
splice()
: This method is used to add/remove elements to/from an array.
2. Number of Arguments.
slice()
: This method can take a maximum of 2 arguments.
Syntax: array.slice(start, end)
start
: It specifies where to start the selection of elements.
end(optional)
: If the 2nd argument provided, elements from the start position up to the end of the array will be returned(excluding the end position).
Example:
let array = [1,2,3,4,5];
array.slice(1) //returns [2,3,4,5]
array.slice(1,3) //returns [2,3]
splice()
: This method can take n arguments.
Syntax: array.splice(start, removeCount, item1, ...., itemN)
start
: It specifies at what position to add/remove items.
removeCount(optional)
: It specifies the number of items to be removed
item1,...itemN(optional)
: Items to be added to the array.
Example:
let array = [1,2,3,4,5];
array.splice(1) //returns [2,3,4,5]
array.splice(1,3) //returns [2,3,4]
array.splice(2,1,6,7); //here it return [3] as it removes the element at index 2.
//console.log(array) is [1,2,6,7,4,5]
3. Return Value:
slice(start, end)
: It returns the array of elements begin with the start and up to the end of the array excluding the end index.
Example:
let array = [1,2,3,4,5];
array.slice(1,3) //returns [2,3]
splice(start, removeCount)
: It returns the array of removed elements begin with start index with number of removeCount.
Example:
let array = [1,2,3,4,5];
array.splice(1,2) //returns [2,3]
4. Mutability:
slice()
: This method doesn't change the original array. But it is considered as Accessor method.
Example:
let array = [1,2,3,4,5];
array.slice(1) //returns [2,3,4,5];
console.log(array) // [1,2,3,4,5]
splice()
: This method is mutator method as it modifies the original array.
Example 1.
let array = [1,2,3,4,5];
array.splice(1,2) //returns [2,3]
console.log(array) // [1,4,5]
Example 2.
let array = [1,2,3,4,5];
array.splice(2,1,6,7) //returns [3]
console.log(array) // [1,2,6,7,4,5]
Thank you.
Top comments (0)