DEV Community

Cover image for What Does `slice(1, -1)` Do?
Lucia Cerchie
Lucia Cerchie

Posted on

What Does `slice(1, -1)` Do?

Today I learned what slice(1, -1) does.

I was looking up ways to (recursively) check if a string is a palindrome, and I came across a solution that used str.slice(1, -1)

slice() is a "returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array." Source

So, if you want to work on an array without mutating it, slice() is a good option.
Alt Text
Since I'd never seen a negative value passed into slice out in the wild, I of course dug deep into the MDN article.

"A negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence."

Turns out, it's a count from the end, similarly to a positive number passed into the first parameter being a count from the beginning.

So, if str = "margherita", str.slice(1, -1 is equal to "argherit". Nifty for all kinds of two-forked approaches. What ways would you use it?

Discussion (1)

Collapse
thesanjeevsharma profile image
Sanjeev Sharma

And just about last night, I was wishing if JS had a feature like Python: str[1:-1]

You found it 😄 Thanks a lot!