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
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