Rahul / March 14, 2023
7 min read • ––– views
It's one of those methods that once you understand and can use it, can make your developer life much easier!
It takes two arguments--a start index and an end index--which determine which part of the array will be returned in the new one.
Both these indexes are completely optional, so if you leave it blank they will default to 0 (the first element) and length (the last element).
By using this powerful method, you can easily retrieve part of an array or string, create substrings and arrays from existing ones, and even remove elements from a given array without mutating it.
As an example, let's say we have an array called
sentenceArray containing a sentence broken down into individual words:
const sentenceArray = ['The', 'slice', 'method', 'is', 'super', 'useful']
sentenceArray.slice(2)--we can create a new array containing all elements starting from index 2:
result = ['method', 'is', 'super', 'useful']. Pretty neat huh?
Stay tuned for more practical examples!
slice() method is used to select a portion of an array. It copies the selected elements from the original array and returns them as a new array.
This makes it easy to pull out only the data you need without having to iterate through the entire array and select the elements by hand.
The syntax for using this method looks like this:
start is the index which specifies where to start slicing (default is 0) and
end is the index at which to end slicing (defaults to array length).
You can also leave out one of either parameter, in which case
end will default as described above.
slice() method, you could write something like this:
const pets = ["dog", "cat", "hamster", "gerbil", "parakeet"]; const dogs = pets.slice(0, 1); // returns ["dog"]
Using the js
slice() in this way, you can quickly and easily organize your data however you need it!
const arr = [1, 2, 3, 4, 5]; const subArr = arr.slice(2, 4); // [3, 4]
In this example, the js
slice() method is used to extract a subarray of arr starting from index 2 and ending at index 4 (exclusive), which gives us the values [3, 4].
const arr = [1, 2, 3, 4, 5]; const newArr = arr.slice(0, 2).concat(arr.slice(3)); // [1, 2, 4, 5]
In this example, the js
slice() method is used to remove the element at index 2 from
We first extract a subarray of
arr containing the elements before the one we want to remove (that is,
[1, 2]) and another subarray containing the elements after the one we want to remove (that is,
We then concatenate these two subarrays using the
concat() method to get the new array
[1, 2, 4, 5].
const str = "Hello, world!"; const subStr = str.slice(0, 5); // "Hello"
In this example, the js
slice() method is used to extract a substring of
str starting from index 0 and ending at index 5 (exclusive), which gives us the string
Have you ever wondered what the difference is between the js
splice() and substring methods? If so, you're not alone.
Let's look at a quick comparison of the three methods to help you understand how they differ.
slice() method extracts a part of an array from the starting index to the end index but does not change the existing array, while
splice() changes the original array by adding/removing elements from it and
substring() extracts characters from a string and does not change the original string.
slice(): This method takes two arguments; startIndex and endIndex. It returns a shallow copy of an array that starts at startIndex and ends before endIndex.
It copies up to but not including endIndex. If startIndex is undefined, this method will copy all elements from beginning to endIndex; if no arguments are provided, then it will return a shallow copy of the entire array.
splice(): This method takes two arguments; startIndex and deleteCount (optional). It removes elements from an array from startIndex up to deleteCount items. It returns an array containing deleted elements or an empty array if no elements were deleted. This method changes the original array as it mutates it by adding/removing specified elements.
substring(): This method takes two arguments; startIndex (optional) and endIndex (optional). It returns characters in a string starting at startIndex until before endIndex without altering or changing the original string. If no arguments are provided, then this method returns a copy of entire string.
Let’s take a look at a few:
- Use positive numbers when referring to the index If you need to refer to elements in an array, it's always best to use positive numbers rather than negative numbers (which start from the end of the array).
This is because if you later change the size of your array, it might throw off your code if you use negative numbers.
- Use If Statement for modifying data in an array
If you’re looking to modify data within an array, use If Statements instead of
Say if you want to delete an element on index two and update all other elements in the array by subtracting one from their index number, use an
if statement combined with
This will give you more control over what happens with each element of your array.
- Convert strings into arrays before using
If your data is stored as a string rather than an array, convert it into an array before using
This will make it easier and faster for browsers to process the data and give you more precise results when performing slices on strings.
Not only is it relatively straightforward to use, but it also has some great features like the ability to work with negative values and the “start” and “end” parameters, making it a very powerful tool.