← Back tothis vs that

slice vs splice

Written byPhuoc Nguyen
Created
01 Aug, 2020
Last updated
07 Aug, 2020
Category
JavaScript
Contributors
munierujp
SanthoshRaju91
`slice` and `splice` are common methods to get a sub-array of a given array.

Differences

  1. The signature of methods are different.
    js
    array.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.
  2. `splice` changes the original array, while `slice` doesn't.
    Given the array of numbers from 1 to 5:
    js
    const array = [1, 2, 3, 4, 5];
    const sub = array.splice(2, 3);

    // The original array is modified
    array; // [1, 2]
    sub; // [3, 4, 5]
    Now, let's pass the same parameters to `slice`:
    js
    const array = [1, 2, 3, 4, 5];
    const sub = array.slice(2, 3);

    // The original array isn't modified
    array; // [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);
If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

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 🥷.
Ask me questions

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