How not to confuse "Slice" with "Splice" in Javascript
This might seem silly to native English speakers — which I’m not — but the resemblance between the two words can often lead to confusion… till you look up and understand the definition of “splice”! :)
The easier one: “slice”!
Think of a slice of bread, or of pizza, and it totally makes sense that the slice method returns a (shallow) copy of a portion of an array, between two optional indices (start = 0, end = array.length):
const array = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
const everything = array.slice() // [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ]
const startingFromSecond = array.slice(1) // [ 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ]
const secondAndThird = array.slice(1, 3) // [ 'Tuesday', 'Wednesday' ]
N.B. Note that the indices of the included elements are greater or equal to start
(0-indexed), but strictly lower than end
.
But what is “splice”??
For instance, when it comes to ropes, splicing means creating joints between two ropes by interweaving the strands, which is consistent with the extra operations linked with the splice method. Indeed, it modifies the content of an array in place by either removing, replacing, or adding new items. The signature looks like this: splice(start, numberOfItemsToDelete = array.length - start, ...optionalItemsToAdd)
, which explains the following outputs:
const array = ['Dog', 'Lion', 'Tiger']
array.splice() // ['Dog', 'Lion', 'Tiger']
array.splice(3) // ['Dog', 'Lion', 'Tiger']
array.splice(1, 1) // ['Dog', 'Tiger']
array.splice(0, 0, 'Elephant') // ['Elephant', 'Dog', 'Tiger']