What slice() method does?
The slice method, as the name suggests, slices an array and returns a copy of the new array. This method does not affect the main array, it just returns the copy of the array. We can give this copy of the array to the main array or to any other array to get the sliced array.
Parameter: It accepts the following two parameters:
- arg1: It refers to the start index from which the method will begin slicing, the start index is inclusive which means if we give 0, it will begin with the 0th index.
- arg2: It refers to the end index. This end index is exclusive which means it will not include the given index in slicing
It is not necessary to give both arguments, if we do not provide the start index, it will start with the 0th index and if we do not provide the end index it will take to the last index.
Return Value: It returns a copy of the new array
Example 1: Here, we are giving the start index as 2 and end index as 4, so it will slice the elements 2, 3. As you can see it returns the copy of the new array, which we are storing in the same array. This method also shortens the array length. Previously array had a length of 4, after slicing the array, it became 2.
4 [ 'upar', 'chopper' ] 2
Example 2: Here we are not giving the end index so it will begin with the 1st index and slice till last.
4 [ 'duper', 'upar', 'chopper' ] 3
What delete() method does?
The delete is more like an operator than the method. It is used to remove the property from the object, it can also remove the data from the array. But it does not remove the references completely which means it does not shorten the array. The delete operator requires the reference to remove the property from that reference.
Example 1: As we can see, we have given the delete operator a reference arr to be removed. But it only removes the property which it was holding. The reference is still there and the length is still 4, it did not shorten our array.
4 [ 'super', <1 empty item>, 'upar', 'chopper' ] 4
Example 2: In this second example. arr reference is still there, only its value is removed, hence the undefined is shown, these deleted memory will be released automatically when there is no reference to the arr is left.
4 The reference arr is still there : undefined [ 'super', 'duper', <1 empty item>, 'chopper' ] 4
Conclusion: If we want to shorten the length of the array, we will use the slice method and if we want to keep the array length the same for some reason, we will use the delete operator.