← Back tothis vs that

slice vs splice

Written byPhuoc Nguyen
Category
JavaScript
Created
01 Aug, 2020
Last updated
07 Aug, 2020
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.
    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:
    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`:
    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:
const clone = (arr) => arr.slice(0);

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

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