Slice or Splice?

Which should you use?

The slice() method in JavaScript is used to extract a section of an array and return it as a new array, without modifying the original array. The method takes two arguments, the first is the starting index and the second is the ending index (not included) of the section to be extracted.

The splice() method, on the other hand, is used to add or remove elements from an array. It takes three arguments, the first is the starting index, the second is the number of elements to be removed, and the third is the element(s) to be added. This method modifies the original array.

Let's say we have this array of todos:

const todos = [
  "Follow @ThePrimeagen on Twitter", 
  "Watch Theos newest video", 
  "Learn the difference between slice and splice"
];

What can we do with slice(...)?

const sliceResult = todos.slice(0, 2);

console.log(sliceResult); 
// Output: ["Follow @ThePrimeagen on Twitter", "Watch Theos newest video"]

console.log(todos); 
// Output: ["Follow @ThePrimeagen on Twitter", "Watch Theos newest video", "Learn the difference between slice and splice"]

See how the original array wasn't modified?

And now splice(...)

const spliceResult = tasks.splice(2, 1, 'Call Elon');

console.log(spliceResult);
// Output: ["Learn the difference between slice and splice"]

console.log(tasks);
// Output: ["Follow @ThePrimeagen on Twitter", "Watch Theos newest video", "Call Elon"]

In summary, slice() creates a new array with a section of the original array, while splice() modifies the original array by adding or removing elements.