Slice and Splice in JavaScript


In slice, the first argument is inclusive and second parameter is exclusive means the index provided in second parameter is not included in slicing.

Note : The slice don’t change the exiting array.

const months = ['Jan', 'Feb', 'Mar', 'Apr'];
months.slice(1,3)     // ['Feb', 'Mar']

Here, the ‘Apr’ is not included in the slice.We get [‘Feb’, ‘Mar’] as an output.

If only one parameter is passed than that number of values will be removed.

const months = ['Jan', 'Feb', 'Mar', 'Apr'];
months.slice(2)     // ['Mar', 'Apr']


Splice will add the values in the array at any specific position provided.
Let’s see with any example.

Note : The splice will change in the exiting array.

const months = ['Jan', 'Feb', 'Mar', 'Apr'];
months.splice(0,2, 'hi')     // ['Mar', 'Apr']

Here, it will return [‘Mar’, ‘Apr’] but in the existing array it will add ‘hi’ instead of [‘Jan’, ‘Feb’] and the updated array will be [“hi”, “Mar”, “Apr”]


Leave a Reply

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

Back to top