Beginner’s Guide to JavaScript slice()

Have you ever ever tried pulling simply a part of an array however ended up tangled in index math or sudden uncomfortable side effects?
We’ve all been there, however the excellent news is there’s a answer and it’s referred to as slice() . Not solely is it cleaner than different workarounds, nevertheless it offers you the precise piece you want with out touching the remainder of the array.
Sounds good, proper?
On this information I’ll break down the fundamentals of how slice() works, in addition to some completely different use case strategies, so you should utilize this in your personal code.
Let’s get into it…
Sidenote: If you wish to study extra about JavaScript, you’ll want to try Andrei’s Complete Web Developer course, in addition to my Beginner and Advanced JavaScript projects:
We’ve the whole lot it is advisable to develop into a full-stack JavaScript developer in 2025.
Graduates from these packages are actually working at Google, Tesla, Amazon, Apple, IBM, Uber, Fb, Shopify + different high tech corporations. There’s no motive why you couldn’t do the identical!
With that out of the way in which, let’s get into this 5-minute tutorial.
What’s slice() and what does it do?
In the event you’ve ever constructed a function that reveals a listing of things akin to merchandise, critiques, or messages you then’ve most likely hit some extent the place you don’t wish to show the whole lot directly.
Possibly you solely wish to present a number of gadgets, then reveal extra later, or simply spotlight the most recent ones. Nicely, that’s precisely the place slice() shines.
slice() permits you to copy a part of an array (i.e. the portion you really want), with out touching the unique knowledge. You inform it the place to start out and the place to cease, and it offers you that precise part again as a brand new array.
That is why builders adore it as a result of it helps you safely reuse knowledge with out inflicting points in different components of your code.
For instance
Let’s say you may have a listing of merchandise:
const merchandise = [
'Laptop',
'Tablet',
'Smartphone',
'Monitor',
'Headphones',
'Camera'
];
And also you’re constructing a product gallery, however you wish to solely present a number of gadgets at first.
Nicely, fairly than messing round with the product array, you should utilize slice() to drag the primary 3 gadgets for this function like so:
// Present the primary 3 gadgets
let visibleProducts = merchandise.slice(0, 3);
console.log(visibleProducts);
// ['Laptop', 'Tablet', 'Smartphone']
So let’s break down how this works.
The primary quantity you cross to slice() is the place to start out, and the second is the place to cease. Nevertheless, in case you’ve simply began out coding, it is advisable to keep in mind that indexes begin at 0 in JavaScript.
Which means that on this case, slice(0, 3) tells JavaScript, “Begin at index 0, and cease earlier than index 3.” Which means you get the primary three gadgets that are positions 0, 1, and a couple of, which on this case are ‘Laptop computer’, ‘Pill’, and ‘Smartphone’.
We are able to even take this additional by including in a number of slice() actions.
For instance
We might simply add some extra code so if the person clicks a “Present Extra” button in your web page, one other slice() reveals the primary 6 (or nonetheless many) gadgets as an alternative.
All we would wish to do is add a slice() for these 6 gadgets like so:
// Present the primary 3 gadgets
let visibleProducts = merchandise.slice(0, 3);
console.log(visibleProducts);
// ['Laptop', 'Tablet', 'Smartphone']
// When the person clicks "Present Extra"
visibleProducts = merchandise.slice(0, 6);
console.log(visibleProducts);
// ['Laptop', 'Tablet', 'Smartphone', 'Monitor', 'Headphones', 'Camera']
Easy, proper?
And bear in mind, that is simply exhibiting the highest six gadgets with out rebuilding the checklist or reloading knowledge from scratch. All you’ve carried out is just sliced a brand new piece of it.
That is only a primary use case although. There’s really a number of other ways we are able to use slice() to seize completely different sections.
seize the remainder of the checklist utilizing slice()
Let’s say that we wished to seize all of the gadgets after a sure level in our checklist.
On this case, all we would wish to do is take away the 2nd quantity from slice(). By doing this it should then mechanically go all the way in which to the tip of the array, beginning at no matter first index you give it.
For instance
Let’s say your checklist has 15 merchandise, and also you wish to checklist the whole lot after the primary 3 that you simply had been previewing, whereas additionally skipping the primary 3.
Nicely then you may merely set the primary index to three and go away the 2nd clean like so:
const allProducts = [
'Laptop', 'Tablet', 'Smartphone', 'Monitor', 'Headphones',
'Camera', 'Keyboard', 'Mouse', 'Speaker', 'Microphone',
'Printer', 'Router', 'Webcam', 'Dock', 'Charger'
];
const remainingProducts = allProducts.slice(3);
console.log(remainingProducts);
// ['Monitor', 'Headphones', 'Camera', 'Keyboard', 'Mouse', 'Speaker', 'Microphone', 'Printer', 'Router', 'Webcam', 'Dock', 'Charger']
Tremendous useful!
This is identical logic that powers infinite scroll feeds, “Load Extra” buttons, and partial previews on nearly each fashionable web site.
This isn’t the one means we are able to use slice() although, so let’s break down another strategies.
use slice() with unfavorable indexes to get gadgets from the tip of a listing
To date, you’ve seen how slice() can seize the primary few gadgets in a listing, which is nice for options like previews and “Present Extra” buttons.
Nevertheless, typically you’ll wish to seize the final gadgets in a listing and that’s the place unfavorable indexes are available. They’re excellent for exhibiting latest merchandise, newest messages, or new uploads.
They’re additionally tremendous easy to make use of. All it is advisable to do is cross a unfavorable quantity to slice(), and JavaScript will begin counting from the tip of the array as an alternative of the start.
For instance
Let’s say you wish to present the final product that was added to your catalog so you’ll be able to show the latest merchandise added to your product checklist.
Nicely, slice(-1) would then seize it for us, like so:
const merchandise = [
'Laptop',
'Tablet',
'Smartphone',
'Monitor',
'Headphones',
'Camera'
];
// Get the most recent product
const newArrivals = merchandise.slice(-1);
console.log(newArrivals);
// ['Camera']
The cool factor about unfavorable indexes like that is that at the same time as you add extra merchandise, it should all the time seize the most recent entry.
Let’s be trustworthy although. Until you’re solely that includes the very newest product, you’d most likely wish to spotlight a number of directly. That means individuals can see a number of new arrivals as an alternative of only one. Fortunately, we are able to do this too by merely including a second unfavorable index to slice().
For instance
Let’s say your product gallery reveals 5 gadgets per web page, and also you wish to load the 5 most up-to-date ones every time. When the person clicks once more, they will scroll again by the subsequent 5 newest gadgets, and so forth.
const merchandise = [
'Laptop', 'Tablet', 'Smartphone', 'Monitor', 'Headphones',
'Camera', 'Keyboard', 'Mouse', 'Speaker', 'Microphone',
'Printer', 'Router', 'Webcam', 'Dock', 'Charger'
];
// Present the final 5 merchandise (the most recent ones)
const latestProducts = merchandise.slice(-5);
console.log(latestProducts);
// ['Printer', 'Router', 'Webcam', 'Dock', 'Charger']
// Present the 5 merchandise earlier than these (scrolling again)
const previousProducts = merchandise.slice(-10, -5);
console.log(previousProducts);
// ['Camera', 'Keyboard', 'Mouse', 'Speaker', 'Microphone']
The primary time it brings up the 5 most up-to-date gadgets. Then when the person clicks once more, it reveals the subsequent 5 and so forth.
Now that you simply’ve seen how slice() can pull simply the part you need, let’s take a look at how you should utilize it to repeat whole arrays safely.
copy a complete array with slice()
Generally, as an alternative of slicing out simply a part of your array, you’ll wish to make a duplicate of the entire thing.
Why?
Nicely keep in mind that slice() doesn’t modify the unique array. It creates a brand-new one, which is ideal for conditions the place it is advisable to change or reorder knowledge with out affecting the supply.
For instance
Let’s say that your product catalog is used throughout a number of components of your website. Possibly your homepage reveals featured merchandise, one other part kinds them by worth, and one other shows them alphabetically.
You wouldn’t need these adjustments to intrude with one another, so as an alternative of sorting or filtering the unique array immediately, you’ll be able to copy it first with slice():
const merchandise = [
{ name: 'Laptop', price: 1200 },
{ name: 'Tablet', price: 800 },
{ name: 'Smartphone', price: 950 },
{ name: 'Monitor', price: 400 },
{ name: 'Headphones', price: 150 }
];
// Copy the complete array, then type the copy
const sortedByPrice = merchandise.slice().type((a, b) => a.worth - b.worth);
console.log(sortedByPrice);
// [
// { name: 'Headphones', price: 150 },
// { name: 'Monitor', price: 400 },
// { name: 'Tablet', price: 800 },
// { name: 'Smartphone', price: 950 },
// { name: 'Laptop', price: 1200 }
// ]
console.log(merchandise);
// [
// { name: 'Laptop', price: 1200 },
// { name: 'Tablet', price: 800 },
// { name: 'Smartphone', price: 950 },
// { name: 'Monitor', price: 400 },
// { name: 'Headphones', price: 150 }
// ]
As you’ll be able to see, merchandise.slice() creates a clear copy of the array, so you’ll be able to then type or filter the copy nonetheless you want with out altering the unique knowledge.
You’ll be able to even take this a bit of additional.
For instance
Let’s say your website reveals merchandise in a number of other ways directly. Possibly by worth, by title, and by latest arrivals, and every of those must type the identical checklist in another way.
Sounds easy sufficient, however in case you tried to reuse and modify the identical array for all three, issues would rapidly get messy. However as a result of slice() offers you a recent copy every time, you’ll be able to safely create separate variations for every view:
const byPrice = merchandise.slice().type((a, b) => a.worth - b.worth);
const byName = merchandise.slice().type((a, b) => a.title.localeCompare(b.title));
const byNewest = merchandise.slice().reverse(); // assuming latest are final added
console.log(byPrice[0].title); // Headphones
console.log(byName[0].title); // Headphones
console.log(byNewest[0].title); // Headphones
And identical to that, you now have 3 completely different product lists, all primarily based on the identical knowledge, however none of them intrude with one another.
Higher nonetheless?
slice() isn’t restricted to only numbers both!
use slice() with strings
To date, we’ve been utilizing slice() with arrays, nevertheless it works simply as nicely with strings.
Why would you apply it to textual content?
As a result of strings are in every single place in JavaScript. Whether or not you’re trimming titles, checking file varieties, formatting timestamps, or creating previews, slice() offers you a clear, predictable strategy to seize precisely what you want with out altering the unique worth.
For instance
Suppose you’re displaying product names or article titles in a grid, however a few of them are too lengthy and begin breaking the format.
You possibly can repair that neatly with a small slice of textual content like so:
const title = "Newbie’s information to mastering JavaScript arrays";
const previewTitle = title.slice(0, 30) + "...";
console.log(previewTitle);
// "Newbie’s information to mastering..."
Right here, “slice(0, 30)“ takes the primary 30 characters of the string and provides an ellipsis to point out that it’s been shortened. The complete textual content stays untouched, which implies you’ll be able to nonetheless present it later when the person expands the view or hovers for particulars.
You may also use slice() to drag out particular particulars from structured textual content.
For instance
In the event you’re checking which file sort a person uploaded:
const filename = "project-report-2025.pdf";
if (filename.slice(-4) === ".pdf") {
console.log("Importing PDF file...");
} else {
console.log("Unsupported file sort.");
}
On this case, slice(-4) grabs the final 4 characters so you’ll be able to examine the file extension earlier than doing the rest. It’s an excellent easy strategy to validate file varieties with out splitting or parsing the entire string.
It’s not the one use case although.
For instance
You possibly can use it to drag structured knowledge like dates from timestamps:
const timestamp = "2025-11-02T10:30:00Z";
const date = timestamp.slice(0, 10);
console.log(date);
// "2025-11-02"
This takes the primary ten characters, leaving you with a clear date format that’s simple to show in an order abstract or dashboard.
Time to check out slice() for your self
As you’ll be able to see, slice() is a type of features that appears easy at first however turns into extremely helpful when you notice how typically you want simply a part of an array or string.
Like something although, you’ll study to make use of it quicker in case you give it a attempt in your personal code!
So why not attempt taking a function you’ve already constructed akin to a gallery, a feed, or perhaps a checklist of things, and refactor it to make use of slice() as an alternative of rebuilding or mutating knowledge. You possibly can experiment with exhibiting just a few gadgets at a time, loading extra when wanted, or grabbing simply the most recent entries.
Don’t fear about masking each edge case immediately. Simply get snug slicing components of your knowledge, seeing how the unique stays untouched, and noticing how a lot cleaner your code feels. As soon as that clicks, you’ll begin recognizing locations throughout your tasks the place slice() could make issues less complicated and extra dependable!
P.S.
Keep in mind, if you wish to study extra about JavaScript, you’ll want to try Andrei’s Complete Web Developer course:
In addition to my Beginner and Advanced JavaScript projects:
We’ve the whole lot it is advisable to develop into a full-stack JavaScript developer in 2025, construct a portfolio, and get employed.
In reality, graduates from these packages are actually working at Google, Tesla, Amazon, Apple, IBM, Uber, Fb, Shopify + different high tech corporations. There’s no motive why you couldn’t do the identical!
As a ZTM member, you get entry to all these programs and extra in a single membership.
Plus, when you be a part of, you may have the chance to from me, different college students and different working tech professionals, in addition to entry to each different course in our library!
Need extra JavaScript content material?
Take a look at a few of my different articles beneath:


