JavaScript slice() Method
Having a good grasp of how different JavaScript string and array methods work is crucial for correct data manipulation across our applications.
The slice()
method is often confused with splice()
, and vice versa. In this article, we are going to take a closer look at the JavaScript slice()
method with code examples. In the upcoming articles in this series, I am going to dive into splice()
, toSpliced()
and split()
methods, and also introduce a comparison overview of all the methods discussed.
๐ก Tip: To get the most out of this article, try answering the ๐ค QUIZ YOURSELF questions in each section before looking at the โ
SOLUTIONS. You can also reinforce your learning by implementing active recall and spaced repetition into your study routine. I also recommend trying out answering questions in the ๐ค Review Questions section at the end of this article before you begin reading. Try answering them if you have come across the slice()
method already, or guess the answers if you are new to the topic.
Array Manipulation With slice()
The slice()
method can be used to manipulate arrays in JavaScript. The most prominent feature of the slice()
method is that it doesn't change the original array. Instead, it copies a given part of it and returns that copied chunk as a new array. In other words, a shallow copy is created, and therefore, we need to assign the sliced array to a new variable.
๐ค QUIZ YOURSELF: Once originalArray
gets sliced, what are the values in originalArray
? And what are the values in newArray
?
const originalArray = ['JavaScript', 'Python', 'Ruby', 'C#'];
const newArray = originalArray.slice(0, 2);
โ SOLUTION
console.log(originalArray); //['JavaScript', 'Python', 'Ruby', 'C#'] console.log(newArray); //['JavaScript', 'Python']
As we can see, originalArray
is not modified and holds the original values, while newArray
contains the sliced elements.Syntax
When it comes to slice()
syntax, we have two options:
array.slice(from, to)
from
denotes the start index, i.e. the index of the element that we want to begin slicing the array from.to
marks the end index, but we need to be careful. The end index will not be included in the sliced array.
๐ค QUIZ YOURSELF: What are the values in newArray
?
const originalArray = ['JavaScript', 'Python', 'Ruby', 'C#'];
const newArray = originalArray.slice(0, 2);
โ SOLUTION
console.log(newArray); //['JavaScript', 'Python']
array.slice(from)
1. As in the example above, from
marks the start index.
2. If we omit the second parameter, we're simply telling JavaScript to grab all elements following the start index.
๐ค QUIZ YOURSELF: What are the values of newArray
?
javascript
const originalArray = ['JavaScript', 'Python', 'Ruby', 'C#'];
const newArray = originalArray.slice(2);
โ SOLUTION
console.log(newArray); //['Ruby', 'C#']
Negative Numbers as Parameters
๐ค QUIZ YOURSELF: What elements are currently present in newArray
?
const originalArray = ['JavaScript', 'Python', 'Ruby', 'C#'];
const newArray = originalArray.slice(-1);
โ SOLUTION
console.log(newArray); //['C#']
๐ค QUIZ YOURSELF: What elements are currently present in newArray
?
const originalArray = ['JavaScript', 'Python', 'Ruby', 'C#'];
const newArray = originalArray.slice(-3);
โ SOLUTION
console.log(newArray); //['Python', 'Ruby', 'C#']
Based on the examples above, we can see that when passing a negative index as an argument, JavaScript will count backward from the end of the array. The last index of an array is always -1
, so if we want to extract the last two elements from it, we'd do it like so: const newArray = originalArray.slice(-2);
.
Passing Bad Arguments to slice()
When Manipulating Arrays
If we pass bad arguments to slice()
, JavaScript will return an empty array. Let's take a look at a few scenarios:
๐ค QUIZ YOURSELF: What will be the values in newArray
if we pass end index that is greater than the length of the array?
const originalArray = ['JavaScript', 'Python', 'Ruby', 'C#'];
const newArray = originalArray.slice(0, 10);
โ SOLUTION
console.log(newArray); //['Python', 'Ruby', 'C#']
In this case, slice()
will begin at index 0
. Although the length of the array is less than the 10
that we passed to it, JavaScript will simply return all the elements in the array. Therefore, in this case, there will be no unexpected behavior.๐ค QUIZ YOURSELF: What will be the values in newArray
if we only pass it start index that is greater than the length of the array?
const originalArray = ['JavaScript', 'Python', 'Ruby', 'C#'];
const newArray = originalArray.slice(10);
โ SOLUTION
console.log(newArray); //[]
We can see that when it comes to the start index, it can never be larger than the length of the array we're slicing. In such case, an empty array will be returned, potentially leading to unexpected behavior as empty arrays are truthy in JavaScript.๐ค QUIZ YOURSELF: What will be the values in newArray
if we pass start and end index that are both greater than the length of the array?
const originalArray = ['JavaScript', 'Python', 'Ruby', 'C#'];
const newArray = originalArray.slice(4, 10);
โ SOLUTION
console.log(newArray); //[]
As in the previous example, we can see that when it comes to the start index, it can never be larger than the length of the array we're slicing.String Manipulation With slice()
slice()
is a method that we can use for manipulating strings as well. The syntax remains the same as in case of array manipulation.
๐ค QUIZ YOURSELF: What is the current value of newString
?
const str = 'Becoming a developer is extremely difficult!'
const str2 = 'Reaching your goals is easy if you stay consistent.'
const newString = str.slice(0, 21).concat(str2.slice(20));
โ SOLUTION
console.log(newString); // Becoming a developer is easy if you stay consistent.
Passing Bad Arguments to slice()
When Manipulating Strings
Similarly to array manipulation, slice()
will return an empty string when passed bad arguments. There is one key and very important difference, though. While empty arrays are truthy in JavaScript, empty strings are falsy. In both string and array manipulation, we should therefore ensure that we're providing correct arguments by, for example, checking the string length and verifying that the start index is not greater than the end index.
๐ค Review Questions
If you were to explain what
slice()
method does in JavaScript to a five-year-old, how would you go about it?What data types can we manipulate with
slice()
in JavaScript?What parameters does
slice()
accept?Does
slice()
change the original array?What does
slice()
return?What happens if we pass negative values as argument/arguments?
What does
slice()
return if passed bad arguments when manipulating arrays?What does
slice()
return if passed bad arguments when manipulating strings?Is there anything we can do to prevent providing incorrect arguments?
Resources
MDN Web Docs: