
endIndex ( optional): the point at which the extraction operation will stop.

The length of an Array is the number of items contained in the array, while the length of a String is the number of characters contained in the string. If the index provided is greater than the length of the parent String or Array, an empty string or empty array is returned as appropriate. If startIndex is undefined, the extraction begins at index 0. Note that indices in JavaScript start at 0.

Simply apply the slice method to a String or an Array, passing in the index where you wish the slice to begin (which is included in the returned copy) and the index where the slice should end (which is not included in the returned copy). SyntaxĪs we see above, the syntax for the slice() method is very straightforward. In the provided string const code, these characters spell ‘love’.

In the example above, the slice() method is used to extract the characters between indices 2 and 6. String.slice() exampleĪpplying the same syntax, it is possible to extract a portion of a String value. In the code above, the slice() method is used to create a copy of the first three numbers of the nums array (as indicated by the provided parameters: 0, 3). Let’s explore how slice() works with Array objects using the following example: const nums = This happens without modifying the original array or string, meaning you essentially get to slice the cake and leave it whole at the same time! Array.slice() example 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.

The slice() method is a part of both the Array and String prototypes, and can be used with either type of object.
