2

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.

ZephDavies
  • 3,964
  • 2
  • 14
  • 19

5 Answers5

5

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

According to docs, Array.prototype.splice returns deleted elements.

It also says that when second parameter deleteCount equals 0 then nothing is deleted.

So, in the first case you are deleting everything after index 0 inclusive and the result is whole array.

In the second case you are deleting 0 elements and the result is empty array.

pwolaq
  • 6,343
  • 19
  • 45
0

The reason the second result is empty is because, if the second parameter is 0 or negative, no elements are removed.

This is of course according to mozzila.

Ivo Silva
  • 367
  • 2
  • 13
0

According to docs, Array.prototype.splice returns deleted elements.

-1

Syntax is:

splice(index, delete, insert)

There is condition actually "if delete part assigning "false" values which are (undefined, 0, false) it will return empty array".

That is why in second syntax returning blank array"

['a','b','c'].splice(0) //returns complete array
['a','b','c'].splice(0, undefined) // Returns []
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Narendra
  • 1,511
  • 1
  • 10
  • 20