Fixing splice() In Older Versions Of Internet Explorer (8 And Olders)

Umar Ashfaq
Eastros
Published in
2 min readMay 29, 2012

When working with Javascript arrays, splice() is an invaluable function that helps conveniently add/remove elements to them. The definition of splice() looks like this:

arrayObj.splice(start, deleteCount, [item1[, item2[, . . . [,itemN]]]]);

So let’s create an array

var nums = [1, 2, 3, 4, 5];

and add some elements to it.

nums.splice(5, 0, 6, 7, 8, 9);
alert(nums); // it will show "1,2,3,4,5,6,7,8,9"

Similarly we can remove some elements from it.

nums.splice(0, 2);
alert(nums); // it will show "3,4,5,6,7,8,9"

IE8 and olders require you to provide atleast first 2 parameters to splice(). If you do not provide second argument (deleteCount), splice() would work without an error, but it would make no effect on your array. Firefox, Chrome and Safari has a more useful approach: if you do not provide second argument (deleteCount), it would keep all the elements till the one at “start” index and remove rest of them.

var alphabets = ['a', 'b', 'c', 'd', 'e', 'f'];
alphabets.splice(3);
alert(alphabets); // it will show "a,b,c"

In my opinion, it is a better approach to keep your logic detached from the implementation details. If you are using splice() in your JS code (you can’t escape it if you are using arrays), it is better that splice() gives you consistent behavior across all of the browsers, instead of you writing separate code to handle abnormal implementations of splice()(as in IE8 and olders). As JS allows us to easily tweak anything we like, anywhere we like, pasting following code somewhere on top of your JS code would ensure that splice() gives you consistent behavior everywhere.

// check if it is IE and it's version is 8 or older
if (document.documentMode && document.documentMode < 9) {

// save original function of splice
var originalSplice = Array.prototype.splice;

// provide a new implementation
Array.prototype.splice = function() {

// since we can't modify 'arguments' array,
// let's create a new one and copy all elements of 'arguments' into it
var arr = [],
i = 0,
max = arguments.length;

for (; i < max; i++){
arr.push(arguments[i]);
}

// if this function had only one argument
// compute 'deleteCount' and push it into arr
if (arr.length==1) {
arr.push(this.length - arr[0]);
}

// invoke original splice() with our new arguments array
return originalSplice.apply(this, arr);
};
}

Comments and suggestions are welcome.

--

--