Friday, 4 April 2014

JavaScript functions slice and splice

In JavaScript, mistaking slice for splice (or vice versa) is a common mistake. These two functions, although they have similar names, are doing two completely different things.

slice:Array’s slice is quite similar to String’s slice. According to the specification, slice needs to accept two arguments, start and end. It will return a new array containing the elements from the given start index up the one right before the specified end index. It’s not very difficult to understand what slice does:

Example:
'abcdefg' .slice(1,2)       // 'b'
'abcdefg' .slice(1,3)       // 'bc'
[1,2,3,4,5] .slice(1,2)     //  [2]
[1,2,3,4,5] .slice(1,3)     //  [2,3]


An important aspect of slice is that it does not change the array which invokes it. The following code fragment illustrates the behavior. As you can see, arr1 keeps its elements and arr2 gets the sliced version thereof.

var arr1 = [1,2,3,4,5];
var arr2 = arr1.slice(1, 2);
console.log(arr1);          // [1,2,3,4,5]
console.log(arr1);          // [2]




splice: Although splice also takes two arguments (at minimum), the meaning is very different:


[1,2,3,4,5] .splice(1,2)     //  [2, 3]



splice also mutates the array that calls it. This is not supposed to be a surprise, after all the name splice implies it.


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


No comments:

Post a Comment