---
title: "4 Ways to Use JavaScript .slice() Method and How to Do Each | CoderPad"
description: "The JavaScript .slice() method is often used in array operations and can be confusing for beginners. This blog post will discuss the JavaScript slice method and four ways to use it. It will also include the code of each method for more clarity."
canonical: "https://coderpad.io/blog/development/4-ways-to-use-javascript-slice-method/"
last_modified: "2026-04-15 16:21:08"
---
[Back to blog](https://coderpad.io/blog/)

# 4 Ways to Use JavaScript .slice() Method and How to Do Each

October 14, 2022 6 Minute Read

By Keshav Malik

[Development](https://coderpad.io/blog/development/)![.slice()](https://coderpad.io/wp-content/uploads/2022/10/coderpad-blogpost-slice-javascript-JSYELLOW-2.png)

The JavaScript`.slice()`method is a common method that’s often used in code but not often understood by novice developers. To help you understand this helpful method, we will discuss exactly what it is and four ways you can use it.

>

![ℹ️](https://coderpad.io/assets/emoji/2139.svg) Before getting started, we assume that you understand how functions work in JavaScript. If not, check out [the JavaScript functions guide](https://coderpad.io/blog/development/what-you-never-learned-about-javascript-functions/) to learn more.

## What is the .slice() method?

Put simply,`.slice()`returns a portion of an array. It’s implementation looks something like this:

```
target.slice(start_index, end_index);Code language: JavaScript (javascript)
```

It takes two arguments:

1. The index of the element to start at.
2. The index of the element to end at.

It then returns an array containing elements from the start index to the end index.

The`start_index`in the method is inclusive (where`start_index`is included), and the`end_index`is exclusive (where`end_index`is not included). This method creates a [shallow copy](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) and does not modify the original array or string.

The`.slice()`method can be helpful when working on a big project:

- The method can be used to quickly and easily extract a portion of an array or string. This function can be very helpful when you need to process only a subset of data.
- Developers can use the`.slice()`method to create a new array or string based on an existing one. This can be helpful when you need to manipulate data in a different way than the original.

## How to use the .slice() method

The`.slice()`method can be used on both arrays and strings (which is just an array of characters). Let’s look at some code examples to understand this better.

```
const arr = [1,2,3,4,5,6,7,8,9,10];
const newArr = arr.slice(3,6);
console.log(newArr);Code language: JavaScript (javascript)
```

Here we have an array of integers named`arr`, and we are using the slice method on it and storing the output of the slice method in a new variable named`newArr`. In this case, the output of the code will be`[4, 5, 6]`. But how?

The start index, in this case, is 3. This means we will start slicing the array from`arr[3]`, which is 4, and we still stop at`arr[6-1]`, which is 6. If you are wondering why we have subtracted 1 from the end index, it is because the end index is always exclusive, which means the end index is not included.

To better understand this concept, let’s look at another example::

```
const arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];
const newArr = arr.slice(3);

console.log(newArr);Code language: JavaScript (javascript)
```

In this code, we don’t have any end index specified because both the start and end indexes are optional, and you can use them per your needs.

When any index is not specified, we assume that the index is either the first element (if the start index is not specified) or the length of the array. Because the index starts from 0, we’ll include all elements until the end of the array ( i.e. where the index is`length-1`).

The output, in this case, will be`["D", "E", "F", "G", "H", "I", "J"]`. The start index is 3, and the end index is not mentioned, so we’ll start slicing from`arr[3]`, which is “ D “. As the end index is not mentioned, we’ll include all elements.

Until now, we only looked at the start and end indexes as positive numbers, but these indexes can be negative ones too.

### Using .slice() with negative indexes

We have the start and end index as negative numbers in the following code block:

```
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const newArr = arr.slice(-3, -1);

console.log(newArr);Code language: JavaScript (javascript)
```

The negative index means we’ll count the index from the end of the array. A negative index can be thought of as an offset from the end of the array, list, or string. For example, in an array with five elements, you can access the last element with an index of -1 (like`arr[-1]`), the second-to-last element with an index of -2, and so on.

The output, in this case, will be`[8, 9]`. The start index is`arr[-3]`, which is 8, and the end index is`arr[-1]`, which is 10. Since the end index is exclusive, the output will be`[8, 9]`.

As we discussed before, both index arguments are optional. Let’s look at a code example with only one negative index argument.

```
const arr = ["A", "B", "C", "D", "E", "F"];
const newArr = arr.slice(-3);

console.log(newArr);Code language: JavaScript (javascript)
```

Here we only have one index specified: -3. We’ll start from`arr[-3]`, which is D, and we’ll include all elements until the end. So the output, in this case, will be`["D", "E", "F"]`.

### Using .slice() on a nested array

We can use the slice method on a nested array as well:

```
var nestedArray = [[1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];
var newArray = nestedArray.slice(1, 3);

console.log(newArray);Code language: JavaScript (javascript)
```

We have a nested array in the above-mentioned code block and are using the slice method on it. In this instance it will print the last two array elements:`[[4,5,6],[7,8,9]]`. You can further access elements based on the index directly like this:

```
var newArray = nestedArray.slice(1, 3)[0]; // Output: [4, 5, 6]Code language: JavaScript (javascript)
```

### Using .slice() without indexes

Developers can also use the slice method without a start or end index, as both are optional. In this case, the output is the shallow copy of the array. Let’s look at the code to understand this better.

```
var array = ["a", "b", "c", "d", "e"];
var output = array.slice() // Using slice without arguments

console.log(output);Code language: PHP (php)
```

Without using any index arguments, this`.slice()`operation would output`'a', 'b', 'c', 'd', 'e'`.

### Using .slice() on strings

As discussed earlier, the slice method can also be used on strings:

```
// Using slice() with any index
const str = "Hello World";
const newStr = str.slice();

console.log(newStr); // Output: "Hello World"

// Using slice() with single index
const newStr2 = str.slice(3); // end index is not specified

console.log(newStr2); // Output: lo World

// Using slice() with start and end index
const newStr3 = str.slice(3, 6);

console.log(newStr3); // Output: lo ( 3rd character is a whitespace )

// Using slice() with one negative & one positive index
const newStr4 = str.slice(0, -1);

console.log(newStr4); // Hello Worl

// Using slice() with only 1 index ( negative )
const newStr5 = str.slice(-3);

console.log(newStr5); // rldCode language: JavaScript (javascript)
```

## Understanding the difference between .slice() and .splice()

In JavaScript,`slice()`and`splice()`are both methods that developers can use to manipulate arrays. However, there is a significant difference between the two methods.

The`.slice()`method returns a new array containing a subset of the elements from the original array. The elements in the new array are selected from the original array based on a start and end index that you specify.

On the other hand, the`. splice()`method modifies the original array.

When you use`.splice()`to add or remove elements from an array, the elements you add or remove are selected based on a start index that you specify.

So, if you want to extract a section of an array without modifying the original array, you would use the`.slice()`method. And if you want to remove a section of an array and get the removed elements back, you would use the`.splice()`method:

```
.splice(start_index, items_to_remove, item_to_insert_1, item_to_insert_2, ...)Code language: CSS (css)
```

With the`.splice()`method, the`start_index`is a required parameter where all others are optional.

In the following code block, we have an array on which we have used both`.splice()`and`.slice()`:

```
const numbers = [1, 2, 3, 4, 5];
const newNumbers = numbers.slice(1, 4);

console.log(newNumbers); // [2, 3, 4]

// Using splice method on the same array

numbers.splice(1, 2);

console.log(numbers); // [1, 4, 5]Code language: JavaScript (javascript)
```

When we used the`.slice()`method, the start index and the end index are 1 and 4, respectively, which gives the output as`[2, 3, 4].`

On the other hand, when we used the`.splice()`method on the same array, we get the output as`[1, 4, 5]`because we are removing two elements from index 1 (i.e., 2 and 3).

## Try it out!

## Conclusion

In this blog post, we explained how you can use JavaScript’s`.slice()`method. This can come in handy when working with arrays and other objects that contain several elements. We’ve also provided a few examples to explain how the method works, using code snippets, as well as how`.slice()`and`.splice()`differ.

We hope this post has been helpful to you, and if you want to learn more about JavaScript or other topics, check out our [blog](https://coderpad.io/blog/).

This post was written by Keshav Malik. [Keshav](https://theinfosecguy.xyz/) is an information security engineer who loves to build and break stuff. He is constantly on the lookout for new and interesting technologies and enjoys working with a diverse set of technologies in his spare time. He loves music and plays badminton whenever the opportunity presents itself.

## Subscribe for more CoderPad insights

## Trending Articles

Previous slide Next slide [Development

## What is Prompt Engineering?

Introducing AI tools such as ChatGPT and Bard helps increase the efficiency of tasks such as data generation, code generation and completion, text summarization, etc. How were these AI tools trained to answer almost every question you ask them? The answer, prompt engineering, is discussed in this blog post.

Read the post](https://coderpad.io/blog/development/what-is-prompt-engineering/) [Development

## A Guide To Using React’s useCallback() Hook

Are you looking to optimize your React applications? Have you heard of the useCallback hook? useCallback is a powerful React hook that helps you optimize your application by preventing unnecessary re-renders. In this post, we'll dive into React's useCallback() hook, define referential equality and callback functions and how to tie it all together.

Read the post](https://coderpad.io/blog/development/a-guide-to-using-reacts-usecallback-hook/) [Development

## MySQL vs. PostgreSQL: How Do They Compare?

A database is a convenient tool that allows users to access information, maintain records, and apply commonly used operations, such as insertion, modification, deletion, and data organization. Learn about MySQL vs PostgreSQL, their features, advantages, and disadvantages. Finally, check out which one is the best choice for you.

Read the post](https://coderpad.io/blog/development/mysql-vs-postgresql-how-do-they-compare/) [Development

## PostgreSQL LIKE Operator: A Detailed Guide

When using databases, searching for values that match a given pattern is a familiar necessity. Learn how you can retrieve entries with queries including a particular string using Postgres LIKE operator.

Read the post](https://coderpad.io/blog/development/postgresql-like-operator-a-detailed-guide/) [Development

## How To Use DataProvider In TestNG With Examples

When it comes to testing there are many tools and techniques available. In this post, we'll discuss how to use DataProvider with TestNG.

Read the post](https://coderpad.io/blog/development/how-to-use-dataprovider-in-testng-with-examples/) [Development

## How To Get Up And Running With Django Migrations: A Guide

Django migrations are a way of handling the application of changes to a database schema. By following the steps outlined in this guide, you can easily set up and use migrations in your Django projects.

Read the post](https://coderpad.io/blog/development/how-to-get-up-and-running-with-django-migrations-a-guide/) [Development

## Writing A Parameterized Test In JUnit With Examples

A JUnit parameterized test allows you to decouple data from structure, generating cleaner and more reliable tests. Learn more in this guide.

Read the post](https://coderpad.io/blog/development/writing-a-parameterized-test-in-junit-with-examples/) [Development

## How To Use Assert In JUnit With Examples

The JUnit Assert class is what you use to write unit testing assertions in JUnit. Learn more about it in this guide, full of examples.

Read the post](https://coderpad.io/blog/development/how-to-use-assert-in-junit-with-examples/) [Development

## A Simple Guide To TypeORM: What It Is And How To Use It

Considering current languages have object-oriented programming features, most database management systems are based on the relational model, with tables instead of objects. For these reasons, mapping relational objects is very important in development. In this article, you will learn what TypeORM, one of the main tools used today, is.

Read the post](https://coderpad.io/blog/development/a-simple-guide-to-typeorm-what-it-is-and-how-to-use-it/) [Development

## Using PreparedStatement in JDBC With Examples

In this post, we'll see why and how to work with JDBC and PreparedStatement. We will also learn along with examples using code.

Read the post](https://coderpad.io/blog/development/using-preparedstatement-in-jdbc-with-examples/) [Development

## React vs React Native: The Differences Explained

React and React Native are similar in that they both allow web developers to build applications based on the unique concept of components. But the two frameworks do this in radically different ways. In this post, we cover the key differences between react and react native frameworks, implementation, and which is an appropriate choice.

Read the post](https://coderpad.io/blog/development/react-vs-react-native-the-differences-explained/) [Development

## Logging in Django

The most challenging part of fixing a problem is identifying it. Unfortunately, this statement is exceptionally true when it comes to debugging. Learn how to use the power of logging into your Django applications to improve your debug process in this article.

Read the post](https://coderpad.io/blog/development/logging-in-django/)

## Hire with confidence.

See why engineering teams trust CoderPad to evaluate developers with realistic, AI-ready hiring workflows.

[Request a demo](https://coderpad.io/sales/)
