Hello Sunil
javascript-slice-feature-image

JavaScript Slice Method – Practical Examples

The JavaScript slice() method is a common method that’s often used in code but not often understood by novice developers.

The slice() method returns a shallow copy of a portion of an array into a new array object.

To help you understand this helpful method, we will discuss exactly what it is and how to use the slice() method using code examples.

Also Read: JavaScript Splice – Delete, Insert, and Replace

Before getting started, we assume that you understand how functions work in JavaScript. If not, check out the JavaScript functions guide to learn more.

So let’s start…

JavaScript Arrays

Firstly, we need to understand how JavaScript arrays work. Arrays are collections of data items stored under a single name. We use arrays when we have to deal with multiple data items.

For example:

//data item collection
var student = ['Sunil', 'Anil', 'Rupa'];
console.log(student);  //['Sunil', 'Anil', 'Rupa']

JavaScript arrays can also contain different type of data at once.

For example:

let array = [1, 2, 3, "hello world", 4.12, true];

This usage is valid in JavaScript. An array with different data types: string, numbers, and a boolean.

JavaScript Slice( ) Method

The slice( ) method copies a given part of an array and returns that copied part as a new array. It doesn’t change the original array.

Syntax:

arr.slice(start, end)

Here, arr is an array.

  • start (optional) – Starting index of the selection. If not provided, the selection starts at start 0.
  • end (optional) – Ending index of the selection (exclusive). If not provided, the selection ends at the index of the last element.

For Example:

let array = [1, 2, 3, "hello world", 4.12, true];

Let’s we want to slice the first three elements from the array above. Since the first element of an array is always indexed at 0, we start slicing from 0.

arr.slice(0, end);

Now here is the tricky part. When we want to slice the first three elements, we must give the end parameter as 3. The slice method doesn’t include the last given element.

array[0] --> 1              // included
array[1] --> 2              // included
array[2] --> 3              // included
array[3] --> "hello world"  // not included

This can create some confusion. That’s why we call the second parameter end.

Finally, we assign the sliced Array to the newArray variable. Now let’s see the result:

let array = [1, 2, 3, "hello world", 4.12, true];
let newArray = array.slice(0,3);
console.log(newArray); //[1, 2, 3]

This simply generates a shallow copy of the original array and it doesn’t modify (immutable) the original array on which it is called upon.

let array = [1, 2, 3, "hello world", 4.12, true];
let newArray = array.slice(0,3);

console.log(newArray); //[1, 2, 3]
console.log(array); //[1, 2, 3, "hello world", 4.12, true];

Let’s take a look at some examples to better understand how the slice() method works.

How to use the slice() method without the start and end parameters [Copy complete array ]

In this first example, we have created a list of cities from around the world. We can use the slice() method to create a shallow copy of that array.

const cities = ["Tokyo","Cairo","Los Angeles","Paris","Seattle"];
console.log(cities.slice()); 
//[ 'Tokyo', 'Cairo', 'Los Angeles', 'Paris', 'Seattle' ]

When we console the result we can see all of the elements from our cities array copied into this new array.

How to use the slice() method using the start parameter [Return a portion of an existing array]

We can use the optional start parameter to set a starting position for selecting elements from the array.

In this example, we will set the start position at index 2 which will select the last three cities in the array and return them in a new array.

const cities = ["Tokyo","Cairo","Los Angeles","Paris","Seattle"];
const newCityArr = cities.slice(2);
console.log(newCityArr); //[ 'Los Angeles', 'Paris', 'Seattle' ]

How to use the slice() method using the start and end parameters

If an end position is specified, then the slice() method will extract elements from the start position up to the end position. The end position will not be included in the extracted elements for the new array.

In this example, we have specified a start index of 2 and end index of 4. The new returned array will only include the cities at index 2 and 3 because the end position is not included in the extracted elements.

const cities = ["Tokyo","Cairo","Los Angeles","Paris","Seattle"];
const newCityArr = cities.slice(2,4);
console.log(newCityArr); //[ 'Los Angeles', 'Paris' ]

How to use the slice() method with negative index

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

The negative index means we will count the index from the end of the array.

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

A negative index can be thought of as an offset from the end of the array list.

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); //[ 'D', 'E', 'F' ]

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

How to use the slice() method on a nested array

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

We have a nested array in the below mentioned code block and are using the slice method on it.

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

console.log(newArray);
//[ [ 4, 5, 6 ], [ 7, 8, 9 ] ]

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 nestedArray = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

var newArray = nestedArray.slice(1, 3)[0];
console.log(newArray); //[ 4, 5, 6 ]

How to use the slice() method on sparse array

When the JavaScript slice method is used on a sparse array, the array returned from slice method may be sparse if the source is sparse.

console.log([1, 2, , 4, 5].slice(1, 4))
// [2, empty, 4]

How to use the slice() method on an array-like Objects into arrays

Now we can go a bit crazy about slicing. Let’s construct an array from a list of arguments passed to a function:

const createArray = (...args) => Array.prototype.slice.call(args);
const array = createArray(1, 2, 3, 4);
console.log(array); // (4) [1, 2, 3, 4]

Here, we received args as a list first, but converted it to an array with rest params …args. We then bound the array to Array.prototype.slice() with Function.prototype.call().

That was easy.

Let’s take one more example:

function TransformToArray(){
  return Array.prototype.slice.call(arguments);
}

var newArray = TransformToArray("1", "2", "3", "4");
console.log(newArray); // ["1", "2", "3", "4"];

Starting position greater than ending position

If we pass in a greater value for start than end, we get an empty array:

const elements = ['A', 'B', 'C', 'D', 'E'];
const result = elements.slice(4, 2);
console.log(result); //[]

Starting position greater than length of array

Likewise, if we pass in a greater value for start than array’s length, we get an empty array:

const elements = ['A', 'B', 'C', 'D', 'E'];
const result = elements.slice(6, 2);
console.log(result); //[]

Conclusion

JavaScript slice method is a powerful and versatile that can be used for cloning an array, copying a portion of an array, and converting an array-like object into an array.

With this guide, you should now have a good understanding of how the slice method works and how to use it in practical examples.

We hope this helps in some small way. Feel free to leave a comment if you can think of another common case worth including.

Resources

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Similar articles you may like

Sunil Pradhan

Hi there 👋 I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.

Add comment

Stay Updated

Want to be notified when our article is published? Enter your email address below to be the first to know.

Sunil Pradhan

Hi there 👋 I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.