21

I can't find it - what if the end param passed to Array.prototype.slice is greater than array length?

I've tested it and it works (in Chrome), but I'm not sure if this is standard behaviour thus can be used commonly?

3 Answers 3

34

If end is greater than the length of the array, it uses the length of the array. From the spec:

If relativeEnd < 0, let final be max((len + relativeEnd),0); else let final be min(relativeEnd, len).

So yes, it's standard behaviour that can be used.


Addressing this part of your question:

I can't find it

I find the quickest way is to search for "mdn array slice" - the first result is usually the relevant documentation page on the Mozilla Developer Network, in this case, this page. Each of these pages has a specifications section, which links through to the right part of the spec. It takes a little bit of getting used to how to read the specs, but it's sometimes useful to dive into them.

Sign up to request clarification or add additional context in comments.

2 Comments

Thx, I've been missing the specifications section, somehow, for all the time;/.
Thank you for sharing your advice about using the specifications section
2

Yes, it is as per the specification.

As per spec

  1. If relativeEnd < 0, let final be max((len + relativeEnd),0); else let final be min(relativeEnd, len).

Which means that final value is min of relativeEnd (end value provided as parameter) and len (length of array).

and

  1. Repeat, while k < final

So, the looping is done till the length of array if the end is not specified.

Comments

0

The array is only copied until min(array.length, endArgument). Yes, this is standardised in §22.1.3.22, and can be trusted to work in every browser.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.