


I'm confident there are many more great examples of using slice - if you have a good one, share it in the comments below! I'll happily update the post. function useOne ( arr ) Wrapping UpĪs you can see by this point, the Array slice method is an incredibly useful tool in your JavaScript toolchest, especially as you start moving towards more functional ways of programming. The simplest way to use the slice method is simply to grab all elements of an array starting at N.Īn example use case might be you want to pop off the first element of an array and use it, returning the remaining array, but you want to do it without modifying the original array. In modern JavaScript it is more idiomatic to use the spread operator for this functionality, but if working in older codebases or without a build step that uses babel you may still want to use slice. Slice without any arguments performs a simple shallow copy. Our first 4 uses highlight the core functionality of slice. It also accepts negative indices, which indicate counts back from the end of the array.

The slice method creates a copy of the array starting at begin up to but not including end. The begin argument is a 0-based index identifying where to begin extraction, while the end argument is a 0-based index identifying where to end. How Javascript Array Slice Worksīefore we dive into some of the more advanced uses, lets look at the basics of the slice method.Īs shown in the MDN documentation, slice isĪ method on an array that takes up to 2 arguments: arr. Slice leaves the original array intact and returns a shallow copy of selected items, splice modifies the original array. In this post we'll master the slice method by example, exploring 8 different ways it can be used.Ĭaution: The slice method is not to be confused with the splice method, which modifies an array in place. Thus it provides a key building block for writing functional JavaScript. The slice method provides a mechanism for creating a shallow copy of a subset of a list, without modifying the original list. The JavaScript array slice method fits both of these criteria.
