Array.splice() Unexpected Behavior When Index Is Undefined

• 1 min read

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' ];

console.log(array);

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

console.log(array);

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

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

1 cheers
Now look what you've done 🌋
Stop clicking and run for your life! 😱
Uh oh, I don't think the system can't handle it! 🔥
Stop it, you're too kind 😄
Thanks for the love! ❤️
Thanks, glad you enjoyed it! Care to share?
Hacker News Reddit

×

Recommended Posts ✍🏻

See All »
• 3 min read
✨ HTML Share Buttons
Read Post »
• 8 min read
🚜 A Simple Web Scraper in Go
Read Post »
• 2 min read
👨🏼‍💻 Going Indie, Again
Read Post »