Array.splice() Unexpected Behavior when Index is Undefined

Today I discovered something you should know about Array.splice() in Javascript. According to this page splice() has a first parameter of index which is supposed to be a number representing the index of the array you wish to splice at. Well, apparently when this index is undefined it acts as though you passed 0 instead.

// Create a sample array
var array = [ 'a', 'b', 'c' ];


// Remove 1 element from index undefined
array.splice(undefined, 1);


 * [ 'a', 'b', 'c' ]
 * [ 'b', 'c' ]

Keep this in mind next time you’re using Array.splice() as it is very unexpected behaviour.

javascript tip