

Convert all elements with the ocean class into the array. When both arguments are passed, the slice method returns a new array starting at the index of the first argument and it ends on the second argument -1 (minus one) of the initial array. To pull off the front of an array, we need to pass two arguments to the Array.slice() method. The first target indexes of an initial array You need to call it with no arguments and save the result to a new variable.Įxample const isWatched = Ĭonst myFriendWatched = isWatched. This is often used to create a copy of an array for further transformations that do not need to change the original array. You can call slice with no arguments at all: arr.slice () creates a copy of the initial array. Let's explore the use of the Array.slice() method. This is similar to the str.slice() string method but returns subarrays instead of substrings.

In this case, the count will be carried out from the end of the array. Note that both indices for start and end could be negative.

It returns a new array into which it copies the elements from index start to end (not including end). And note that the original array is not modified. According to the MDN Web Docs documentation, the Array.slice() method, in particular, sends back a shallow copy of a certain part of an array to a brand new array object, that is selected from beginning to end (not including an end). Operators: Addition assignment operator (+=)Īrrays provide many methods.And you're equipped with a handy mnemonic, that splice compared to slice has an additional letter, 'p', which helps you remember that splice mutates and optionally adds or removes from the original array. You now know that slice makes a shallow copy of the original array, while splice mutates the original array and optionally adds or removes elements. ConclusionĪnd there we have it! This blog goes over the differences between slice and splice. And because splice can add and remove stuff to the original array, that means that it also mutates the original array. Because of the extra letter, I associate the additional letter to splice's use of adding or removing from the original array. splice has an extra letter, 'p', compared to slice.

I remember the difference between slice and splice using a mnemonic. insert 'juliet' and 'zeke' at 3rd index // returns Ĭonsole. As its name suggests, it takes a slice from the entity it is applied to. The method returns items (from arrays) or characters (from strings) according to the provided indices. splice ( 3, 1, 'juliet', 'zeke' ) // remove 'harper'. The slice () method is a part of both the Array and String prototypes, and can be used with either type of object.
