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?

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

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!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more