DEV Community

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

Posted on

7 1

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?

Image of AssemblyAI

Automatic Speech Recognition with AssemblyAI

Experience near-human accuracy, low-latency performance, and advanced Speech AI capabilities with AssemblyAI's Speech-to-Text API. Sign up today and get $50 in API credit. No credit card required.

Try the API

Top comments (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!

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay