This bugs needs to be fixed

[1,2,3,4,5].slice(-([1,2,3,4,5].length-1)) // [2,3,4,5]
[1,2].slice(-([1,2].length-1)) //[2]
[1].slice(-([1].length-1)) // You would think []? No: [1]!

Syntax sugar (which is the ability to use "substr" with a minus sign) is supposed to help the developer, not to confuse him with inconsistent logics.

The solution could be simple:

[1,2,3,4,5].slice(0) // [1,2,3,4,5];
[1,2,3,4,5].slice(-0) // [];

The risk of changing this now is that there could be existing code that relies of both 0 and -0 having the same behavior. Generally speaking ECMAScript tired to remain backwards compatible so that older websites continue to work in newer browsers.

For the example why not:

[1,2,3,4,5].slice(1) // [2,3,4,5]
[1,2].slice(1) // [2]
[1].slice(1) // []

Your solution is good, but what's the point of using substr with a minus sign if we need to switch to the plus one in order to ensure the stable work of the program? Maybe the usage of minus sign should be discouraged (while being allowed for backwards compatibility)?

The minus signs work great and are very convenient if you're dealing with numeric literals. If you're not dealing with literals, and are instead trying to autogenerated the index from a different number, the. Yeah, you need to watch out for the zero case.

1 Like

Yeah, for example when wanting the last two values:

[1,2,3,4,5].slice(-2) // [4,5]
[1,2].slice(-2) // [1,2]
[1].slice(-2) // [1]
1 Like

(you keep using the term “substr”, which doesn’t apply to arrays - this is “slice”)

1 Like