JavaScript Slice and Splice

Slice in JavaScript allows you to remove items from the beginning and end of an array. The first parameter passed in to the slice function is the position of the array to start the slice operation. Remember, the first position of the array is the index 0. This position can be passed in to the slice function as a positive integer (start from the front of the array) or negative integer (start from the end of the array). Take a look at this example:

const ages = [1, 2, 3, 4];

console.log(ages.slice(1)); // returns [2, 3, 4]
console.log(ages.slice(-1)); // returns [4]

The slice function takes a section parameter. That is, the position to end the slice operation. Here is an example how this works:

const ages = [1, 2, 3, 4];

console.log(ages.slice(1, 2)); // returns [2]
console.log(ages.slice(1, 4)); // returns [2, 3, 4]

Important to note! The slice function does not alter the original array. It returns a new array.

const ages = [1, 2, 3, 4];

console.log(ages.slice(1, 2)); // returns [2]
console.log(ages); // returns [1, 2, 3, 4]

Splice

If you want to remove or even add items to an array, splice is what you need. splice however, in contrast to slice modifies the array and returns the items that were removed. Slice takes 2 arguments, the starting index and how many items to remove. Let’s look at an example:

const ages = [1, 2, 3, 4];

console.log(ages.splice(1, 2)); // returns [2, 3]
console.log(ages); // returns [1, 4]

If you pass additional arguments to splice, then it will add them to the array in the position of where the items were removed. Here is how that works:

const ages = [1, 2, 3, 4];

console.log(ages.splice(1, 2, 5, "Six")); // returns [2, 3]
console.log(ages); // returns [1, 5, "Six", 4]


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *