Slice Vs Splice In JavaScript Array

avatar


image.png

Image Source

Slicing is used to get a new array from an existing array without modifying the original array. Slicing always returns a new array. The basic syntax of slicing an array in JavaScript is:

array_name.slice(starting_index, ending_index)
array_name.slice()
array_name.slice(starting_index)

If you omit the starting and ending index, then the array will be sliced starting from index 0 till its length. If you specify just the starting index and not the ending index then it will create a new array from where the index is specified upto the length of an array. Lets see the example of each syntax. The statement after //=> is the output that you can see in your browser console.

<script>
    var chicken_dish = ["Drumstick", "Roast", "Nugget", "Tandoori", "Grilled wings", "Crispy Chicken"];
    var chicken_dish1 = chicken_dish.slice(0);
    console.log(chicken_dish1); //=> ["Drumstick", "Roast", "Nugget", "Tandoori", "Grilled wings", "Crispy Chicken"]
    var chicken_dish2 = chicken_dish.slice(3); 
    console.log(chicken_dish2); //=> ["Tandoori", "Grilled wings", "Crispy Chicken"]
    var chicken_dish3 = chickem_dish.slice(1, 4); 
    console.log(chicken_dish3); //=> ["Roast", "Nugget", "Tandoori"]
</script>

Now lets see the similar built-in function like slice() in JavaScript which is splice(). Both of them sounds similar but their way of working is different. While slice() doesn't affect original array after slicing, splice() modifies the original array. It is basically used to remove or replace/modify an existing value in an array. Lets see this with an example.

<script>
    var arr1 = [1, 2, 3, 4, 5];
    var arr2 = arr1.splice(2);
    console.log(arr2); //=>[3, 4, 5]
    console.log(arr1); //=> [1,2]
</script>

You can also specify the starting index and ending index for this function as well i.e. from where you want to start removing the item and where you want to end it. As stated before, lets see a simple code in which this function is used to modify/replace an item in an array.

<script>
    var arr1 = [1, 2, 3, 4, 5];
    var arr2 = arr1.splice(1,2,6,7); // This will put 6 and 7 in index number 1 and 2 respectively after removing.
    console.log(arr2); //=> [2,3] Removing item in index 1 and 2
    console.log(arr1); //=> [1,6,7,4,5] The original array is modified
</script>

So this is the basic difference between slice() and splice() in JavaScript. If you know more about this please feel free to comment down so that I also know other things about this as well since I am also beginner in the field of learning JavaScript.



0
0
0.000
0 comments