javascriptarrayssplice

splice(0) vs splice(0,undefined)


Splice with no second argument behaves as expected:

['a','b','c'].splice(0)            // Returns ['a','b','c']

But Splice with a undefined second argument behaves differently:

['a','b','c'].splice(0, undefined) // Returns []

Can someone explain to me the difference? I would expect the same (first) result.

It suggests that internally, splice is using "arguments.length" or similar, to change its behaviour, rather than checking the arguments.


Solution

  • It suggests that internally, splice is using "arguments.length" or similar

    Yes, that's exactly what happens internally.

    If there is exactly one argument passed, it removes all elements until the end.
    If there are more arguments passed, it takes the second one, casts it to an integer and uses it for the count of elements to be deleted. When you are passing undefined, it is cast to the number value NaN, which leads to the integer 0 - no elements are removed.