Use Code: BFCM25 to get 66% OFF your annual membership. Expires soon 👇

Beginner’s Guide to JavaScript slice()

Jacinto Wong
Jacinto Wong
hero image

Have you ever tried pulling just part of an array but ended up tangled in index math or unexpected side effects? 

We’ve all been there, but the good news is there is a solution and it’s called slice() . Not only is it cleaner than other workarounds, but it gives you the exact piece you need without touching the rest of the array.

Sounds good, right?

In this guide I’ll break down the basics of how slice() works, as well as some different use case methods, so you can use this in your own code.

Let’s get into it…

Sidenote: If you want to learn more about JavaScript, be sure to check out Andrei’s Complete Web Developer course, as well as my Beginner and Advanced JavaScript projects:

We have everything you need to become a full-stack JavaScript developer in 2025.

Graduates from these programs are now working at Google, Tesla, Amazon, Apple, IBM, Uber, Facebook, Shopify + other top tech companies. There’s no reason why you couldn’t do the same!

With that out of the way, let’s get into this 5-minute tutorial.

What is slice() and what does it do?

If you’ve ever built a feature that shows a list of items such as products, reviews, or messages then you’ve probably hit a point where you don’t want to display everything at once.

Maybe you only want to show a few items, then reveal more later, or just highlight the newest ones. Well, that’s exactly where slice() shines.

slice() lets you copy part of an array (i.e. the portion you actually need), without touching the original data. You tell it where to start and where to stop, and it gives you that exact section back as a new array.

This is why developers love it because it helps you safely reuse data without causing issues in other parts of your code.

For example

Let’s say you have a list of products:

const products = [
  'Laptop',
  'Tablet',
  'Smartphone',
  'Monitor',
  'Headphones',
  'Camera'
];

And you’re building a product gallery, but you want to only show a few items at first. 

Well, rather than messing around with the product array, you can use slice() to pull the first 3 items for this feature like so:

// Show the first 3 items
let visibleProducts = products.slice(0, 3);

console.log(visibleProducts);
// ['Laptop', 'Tablet', 'Smartphone']

So let’s break down how this works.

The first number you pass to slice() is where to start, and the second is where to stop. However, if you’ve just started out coding, you need to remember that indexes start at 0 in JavaScript. 

This means that in this case, slice(0, 3) tells JavaScript, “Start at index 0, and stop before index 3.” That means you get the first three items which are positions 0, 1, and 2,  which in this case are 'Laptop', 'Tablet', and 'Smartphone'.

We can even take this further by adding in multiple slice() actions.

For example

We could easily add some additional code so if the user clicks a “Show More” button on your page, another slice() shows the first 6 (or however many) items instead.

All we would need to do is add a slice() for those 6 items like so:

// Show the first 3 items
let visibleProducts = products.slice(0, 3);

console.log(visibleProducts);
// ['Laptop', 'Tablet', 'Smartphone']


// When the user clicks "Show More"
visibleProducts = products.slice(0, 6);

console.log(visibleProducts);
// ['Laptop', 'Tablet', 'Smartphone', 'Monitor', 'Headphones', 'Camera']

Simple, right?

And remember, this is just showing the top six items without rebuilding the list or reloading data from scratch. All you’ve done is simply sliced a new piece of it.

This is just a basic use case though. There’s actually a few different ways we can use slice() to grab different sections.

How to grab the rest of the list using slice()

Let’s say that we wanted to grab all the items after a certain point in our list.

In this case, all we would need to do is remove the 2nd number from slice(). By doing this it will then automatically go all the way to the end of the array, starting at whatever first index you give it.

For example

Let’s say your list has 15 products, and you want to list everything after the first 3 that you had been previewing, while also skipping the first 3.

Well then you could simply set the first index to 3 and leave the 2nd blank 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']

Super handy!

This is the same logic that powers infinite scroll feeds, “Load More” buttons, and partial previews on almost every modern website.

This isn’t the only way we can use slice() though, so let’s break down some other methods.

How to use slice() with negative indexes to get items from the end of a list

So far, you’ve seen how slice() can grab the first few items in a list, which is great for features like previews and “Show More” buttons.

However, sometimes you’ll want to grab the last items in a list and that’s where negative indexes come in. They’re perfect for showing recent products, latest messages, or new uploads.

They’re also super simple to use. All you need to do is pass a negative number to slice(), and JavaScript will start counting from the end of the array instead of the beginning.

For example

Let’s say you want to show the last product that was added to your catalog so you can display the most recent item added to your product list.

Well,  slice(-1) would then grab it for us, like so:

const products = [
  'Laptop',
  'Tablet',
  'Smartphone',
  'Monitor',
  'Headphones',
  'Camera'
];


// Get the latest product
const newArrivals = products.slice(-1);

console.log(newArrivals);
// ['Camera']

The cool thing about negative indexes like this is that even as you add more products, it will always grab the latest entry.

Let’s be honest though. Unless you’re only featuring the very latest product, you’d probably want to highlight a few at once. That way people can see several new arrivals instead of just one. Luckily, we can do that too by simply adding a second negative index to slice().

For example

Let’s say your product gallery shows 5 items per page, and you want to load the 5 most recent ones each time. When the user clicks again, they can scroll back through the next 5 latest items, and so on.

const products = [
  'Laptop', 'Tablet', 'Smartphone', 'Monitor', 'Headphones',
  'Camera', 'Keyboard', 'Mouse', 'Speaker', 'Microphone',
  'Printer', 'Router', 'Webcam', 'Dock', 'Charger'
];


// Show the last 5 products (the newest ones)
const latestProducts = products.slice(-5);
console.log(latestProducts);
// ['Printer', 'Router', 'Webcam', 'Dock', 'Charger']


// Show the 5 products before those (scrolling back)
const previousProducts = products.slice(-10, -5);
console.log(previousProducts);
// ['Camera', 'Keyboard', 'Mouse', 'Speaker', 'Microphone']

The first time it brings up the 5 most recent items. Then when the user clicks again, it shows the next 5 and so on.

Now that you’ve seen how slice() can pull just the section you want, let’s look at how you can use it to copy entire arrays safely.

How to copy an entire array with slice()

Sometimes, instead of slicing out just part of your array, you’ll want to make a copy of the whole thing.

Why? 

Well remember that slice() doesn’t modify the original array. It creates a brand-new one, which is perfect for situations where you need to change or reorder data without affecting the source.

For example

Let’s say that your product catalog is used across several parts of your site. Maybe your homepage shows featured products, another section sorts them by price, and another displays them alphabetically.

You wouldn’t want those changes to interfere with each other, so instead of sorting or filtering the original array directly, you can copy it first with slice():

const products = [
  { name: 'Laptop', price: 1200 },
  { name: 'Tablet', price: 800 },
  { name: 'Smartphone', price: 950 },
  { name: 'Monitor', price: 400 },
  { name: 'Headphones', price: 150 }
];

// Copy the full array, then sort the copy
const sortedByPrice = products.slice().sort((a, b) => a.price - b.price);

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(products);
// [
//   { name: 'Laptop', price: 1200 },
//   { name: 'Tablet', price: 800 },
//   { name: 'Smartphone', price: 950 },
//   { name: 'Monitor', price: 400 },
//   { name: 'Headphones', price: 150 }
// ]

As you can see, products.slice() creates a clean copy of the array, so you can then sort or filter the copy however you like without changing the original data.

You can even take this a little further. 

For example

Let’s say your site shows products in a few different ways at once. Maybe by price, by name, and by newest arrivals, and each of these needs to sort the same list differently.

Sounds simple enough, but if you tried to reuse and modify the same array for all three, things would quickly get messy. But because slice() gives you a fresh copy each time, you can safely create separate versions for each view:

const byPrice = products.slice().sort((a, b) => a.price - b.price);
const byName = products.slice().sort((a, b) => a.name.localeCompare(b.name));
const byNewest = products.slice().reverse(); // assuming newest are last added

console.log(byPrice[0].name);  // Headphones
console.log(byName[0].name);   // Headphones
console.log(byNewest[0].name); // Headphones
And just like that, you now have 3 different product lists, all based on the same data, but none of them interfere with each other.

Better still?

slice() isn’t limited to just numbers either!

How to use slice() with strings

So far, we’ve been using slice() with arrays, but it works just as well with strings.

Why would you use it on text? 

Because strings are everywhere in JavaScript. Whether you’re trimming titles, checking file types, formatting timestamps, or creating previews, slice() gives you a clean, predictable way to grab exactly what you need without changing the original value.

For example

Suppose you’re displaying product names or article titles in a grid, but some of them are too long and start breaking the layout. 

You could fix that neatly with a small slice of text like so:

const title = "Beginner’s guide to mastering JavaScript arrays";
const previewTitle = title.slice(0, 30) + "...";

console.log(previewTitle);
// "Beginner’s guide to mastering..."
Here, ``slice(0, 30)`` takes the first 30 characters of the string and adds an ellipsis to show that it’s been shortened. The full text remains untouched, which means you can still show it later when the user expands the view or hovers for details.

You can also use slice() to pull out specific details from structured text.

For example

If you’re checking which file type a user uploaded:

const filename = "project-report-2025.pdf";

if (filename.slice(-4) === ".pdf") {
  console.log("Uploading PDF file...");
} else {
  console.log("Unsupported file type.");
}

In this case, slice(-4) grabs the last four characters so you can check the file extension before doing anything else. It’s a super simple way to validate file types without splitting or parsing the whole string.

It’s not the only use case though.

For example

You could use it to pull structured data 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 first ten characters, leaving you with a clean date format that’s easy to display in an order summary or dashboard.

Time to test out slice() for yourself

As you can see, slice() is one of those functions that seems simple at first but becomes incredibly useful once you realize how often you need just part of an array or string.

Like anything though, you’ll learn to use it faster if you give it a try in your own code!

So why not try taking a feature you’ve already built such as a gallery, a feed, or even a list of items, and refactor it to use slice() instead of rebuilding or mutating data. You could experiment with showing only a few items at a time, loading more when needed, or grabbing just the newest entries.

Don’t worry about covering every edge case right away. Just get comfortable slicing parts of your data, seeing how the original stays untouched, and noticing how much cleaner your code feels. Once that clicks, you’ll start spotting places all over your projects where slice() can make things simpler and more reliable!

P.S.

Remember, if you want to learn more about JavaScript, be sure to check out Andrei’s Complete Web Developer course:

As well as my Beginner and Advanced JavaScript projects:

We have everything you need to become a full-stack JavaScript developer in 2025, build a portfolio, and get hired.

In fact, graduates from these programs are now working at Google, Tesla, Amazon, Apple, IBM, Uber, Facebook, Shopify + other top tech companies. There’s no reason why you couldn’t do the same!

As a ZTM member, you get access to all these courses and more in a single membership.

Plus, once you join, you'll have the opportunity to from me, other students and other working tech professionals, as well as access to every other course in our library!

Want more JavaScript content?

Check out some of my other articles below:

More from Zero To Mastery

How to Become a Full-Stack Web Developer & Get Hired in 2025 preview
How to Become a Full-Stack Web Developer & Get Hired in 2025
32 min read

Learn everything you need to know to become a Full-Stack Web Developer, as well as how to get hired as one in 2025 with this step-by-step guide!

CSS vs HTML: Comparison Guide (With Code Examples) preview
CSS vs HTML: Comparison Guide (With Code Examples)
24 min read

HTML vs CSS. Learn their differences, pros, and cons, and how to use them with different variables for dynamic site creation!

Beginners Guide To Flexbox With Bootstrap preview
Popular
Beginners Guide To Flexbox With Bootstrap
15 min read

Learn how to use Flexbox features for responsive design inside of Bootstrap. I've also included some code examples to show you how easy it is to start using!