

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. Negative indices are also supported and will be counted from the end.The slice() method is a part of both the Array and String prototypes, and can be used with either type of object. It takes two parameters, startIndex (inclusive) and endIndex (exclusive), which can be omitted to slice from the start index to the last element of the array. The `slice` method in JavaScript is a useful tool for extracting portions of an array without modifying the original. Let newArray = array.slice(-3, -1) // Slice from the third last element to the last element.

Keep in mind that if you provide negative indices, they’ll be counted from the end: Let newArray = array.slice(2) // Slicing from index 2 (inclusive) to the end of the array In that case, it will slice the array from startIndex to the last element of the array. Slice from index 1 (inclusive) to index 4 (exclusive)Ĭonsole.log(newArray) // Output: Ĭonsole.log(array) // Output:, Original array is not modified Here’s how to use the `slice` method in JavaScript: It creates a new array that has elements starting from the specified begin index (inclusive) up to, but not including, the end index (exclusive). The Array `slice` method in JavaScript is used to extract a portion of an array, without modifying the original array. In this blog post we’ll explore how to use this useful method with examples. Negative indices are also supported and they’ll be counted from the end. You can also omit the endIndex and it will slice from startIndex to the last element of the array. The `slice` method in JavaScript is a powerful tool for extracting portions of an array without modifying the original.
