Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should be the value of [1,2,3].slice(1,undefined)?

I found a difference in the handling of

[1,2,3].slice(1, undefined)

between chrome (that returns [2,3]) and firefox (that returns []).

Both of course instead agree on [2, 3] as the value of

[1,2,3].slice(1)

and they also both agree on [] as the value of

[1,2,3].slice(1, null)

Which of the two is correct? Or may be this not clearly specified in the standard?

like image 359
6502 Avatar asked Dec 05 '22 20:12

6502


2 Answers

The specification says:

7. If end is undefined, let relativeEnd be len; else let relativeEnd be ToInteger(end).

Which Firefox version are you using? Firefox 5 gives me correctly [2, 3]. Update: Firefox 3.6 returns indeed an empty array.

I don't know what is wrong here, because if you call slice() without a second parameter, end will be undefined too.

Update:

After playing around a bit, it seems that an empty array is returned if the second parameter passed to .slice() is NaN. Example (+undefined returns NaN):

> [1,2,3].slice(1, +undefined)
> []

This is the same in Firefox and in Chrome.

Unfortunately, this is also not conform to the specification, as ToInteger(NaN) [spec] should return 0, so the the array should actually be sliced to the end.

I don't claim that this is the reason why it does not work properly in some Firefox versions, I don't know the implementation.

Incident of minor disorientation... never mind.

like image 179
Felix Kling Avatar answered Dec 28 '22 21:12

Felix Kling


I'm not sure if that is defined on the standard, but I can tell you that is a tricky invocation. Like Felix says, it's not standard behaviour, but I can think of why it's like that.

As you may know undefined is the value set to parameters that are not supplied when a function is called. In your example however, you are actually passing undefined, so the arguments passed are actually two and is reflected in arguments.length.

So from what you say happens it's easy to imagine that in Chrome, the second parameter is being checked with typeof param2 == "undefined"and in Firefox they use arguments.length > 1. So it's not (entirely) that Firefox got it wrong, like Felix suggests, they just assume undefined would never actually be passed in directly as the 2nd parameter.

You'll probably run into several of this cases using undefined like that, I'd recommend you dont use it!

like image 21
Juan Avatar answered Dec 28 '22 20:12

Juan