slice vs splice
Written byPhuoc Nguyen
Created
01 Aug, 2020
Last updated
07 Aug, 2020
Category
JavaScript
`slice`
and `splice`
are common methods to get a sub-array of a given array.#Differences
-
The signature of methods are different.jsarray.slice(startingIndex, endingIndex);array.splice(startingIndex, length, ...items);While the first parameter are the same as each other indicating the starting index of removed elements, the second parameters aren't.The second parameter of
`slice`
and`splice`
are the ending index and the number of sub items, respectively.With the`splice`
method, it's possible to keep the items not to be removed from the original array by passing them to the last parameters. -
`splice`
changes the original array, while`slice`
doesn't.Given the array of numbers from 1 to 5:jsconst array = [1, 2, 3, 4, 5];const sub = array.splice(2, 3);// The original array is modifiedarray; // [1, 2]sub; // [3, 4, 5]Now, let's pass the same parameters to`slice`
:jsconst array = [1, 2, 3, 4, 5];const sub = array.slice(2, 3);// The original array isn't modifiedarray; // [1, 2, 3, 4, 5]sub; // [3]
#Tip
We can clone an array by ignoring the ending index:
js
const clone = (arr) => arr.slice(0);
Questions? 🙋
Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Recent posts ⚡
Newsletter 🔔
If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn