
Ideally, the user of your module should not always read the documentation to figure out which one they really want. When you build your own module, it is important to choose an API which minimizes this slice vs splice confusion. This is not supposed to be a surprise, after all the name splice implies it. On top of that, splice also mutates the array that calls it. var x = Īlthough splice (Section 15.4.4.12) also takes two arguments (at minimum), the meaning is very different. As you can see, x keeps its elements and y gets the sliced version thereof. The following code fragment illustrates the behavior. It’s not very difficult to understand what slice does: 'abc'.slice(1,2) // "b"Īn important aspect of slice is that it does not change the array which invokes it. It will return a new array containing the elements from the given start index up the one right before the specified end index. According to the specification, slice needs to accept two arguments, start and end.


In practice, such a confusion can be avoided by choosing an API that telegraphs the const-correctness of the function.Īrray’s slice (ECMAScript 5.1 Specification Section 15.4.4.10) is quite similar to String’s slice. These two functions, although they have similar names, are doing two completely different things. In JavaScript, mistaking slice for splice (or vice versa) is a common mistake among rookies and even experts.

Ariya.io About Talks Articles JavaScript Array: slice vs splice
