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
🚅 Next Stop, Yaak
Read Post »
• 3 min read
⛰ïļ 2022 Recap: Getting Physical
Read Post »
• 5 min read
ðŸŠī Home-Grown Web Analytics
Read Post »