Slice() and Splice() methods in JavaScript

Easy Guide to Understanding slice() and splice() in JavaScript

When you work with lists in JavaScript, it’s good to know how to change them in different ways. Two ways to do this are with slice() and splice(). These methods sound alike but do different things. Let’s look at them in a very easy way.

What is slice()?

Think of having a pizza and only wanting a few pieces without touching the rest. That’s what slice() does. It takes part of a list and makes a new list from it, but it doesn’t change the original list.

How it works:

let fruits = ['apple', 'banana', 'cherry', 'date'];
let someFruits = fruits.slice(1, 3); // takes 'banana' and 'cherry'
  • Start: Where you begin (at the 1st spot here).
  • End: Where you stop (at the 3rd spot here, but it doesn’t count this one).

Now you have a new list ['banana', 'cherry'], and your first list fruits is still the same.

What is splice()?

Suppose you want to do more than just take some pieces. Maybe you want to take out some items or add new ones. That’s what splice() does. It changes the first list by adding, removing, or replacing items.

How it works:

let fruits = ['apple', 'banana', 'cherry', 'date'];
fruits.splice(1, 2, 'blackberry', 'orange'); // Replaces 'banana' and 'cherry' with 'blackberry' and 'orange'
  • Start: Where you begin changing the list (at the 1st spot here).
  • How many to take out: How many items you want to remove (2 here).
  • What to add: The new items you want to add.

Now, the list fruits looks like this: ['apple', 'blackberry', 'orange', 'date'].

Key Differences

  • Changing the List: splice() changes the first list, while slice() does not.
  • What you get back: slice() returns a new list with the pieces you took. splice() gives back a list of the items that were taken out.

When to Use Each

  • Use slice() when you need parts of a list for something but don’t want to change the first list.
  • Use splice() when you need to change the first list directly, like adding or removing items.

Conclusion

To remember the difference between slice() and splice(), think of this easy line: “Slice to look, splice to change.” This means you use slice() to look at parts of the list and splice() to change it.

Leave a Reply