DEV Community

Rudra Pratap
Rudra Pratap

Posted on • Edited on

A quick breakdown of the slice() Method in JavaScript

In this article, I am writing in detail the working of slice.

slice

  • Syntax: slice(start, end)
  • slice is a method on array object which is used to return a shallow array of a section of the original array.

  • slice accepts two parameters: start and end
    By default start=0 and end=array.length, and both are optional.

  • slice does not mutates the original array.

  • The start and end values can be negative too. In that case array.length is added to them.
    That is:
    if(start<0) start=start+array.size();
    if(end<0) end=end+array.size();

  • If the input range is not valid (for example: start >= end ) then an empty array([]) is returned.

  • The range of the output array is [ start, end ). That is, the start index is included but not the end index.


let arr = [1,2,3,4,5]
console.log(arr.slice(2,4)) // [ 3, 4 ]
Enter fullscreen mode Exit fullscreen mode

Here, the start is 2 and end is 4. Element at 2nd index is 3 and element at 4th index is 5. All the elements between the indices [2,4) will be included ie [3,4].



let arr = [1,2,3,4,5]
console.log(arr.slice(2)) // [ 3, 4, 5 ]
Enter fullscreen mode Exit fullscreen mode

Here, the end parameter is not specified, therefore its default value will be used ie array.length which is 5, as a result the resulting array will contain all the elements between the indices [2,5). Therefore the result is [3,4,5]



let arr = [1,2,3,4,5]
console.log(arr.slice(-1)) // [ 5 ]
Enter fullscreen mode Exit fullscreen mode

Here, the start parameter is -1 which is negative therefore this start variable is converted into start+array.length. That is the final value of start = -1 + 5 => 4. Since the end parameter is not provided, therefore its default value, ie, 5 (array.length) is used.
Hence arr.slice(-1) is transformed into arr.slice(4,5), which results into [5].



Some more examples to grasp the concept
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// Expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]

console.log(animals.slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

console.log(animals.slice(-1));
// Expected output: Array ["elephant"]

Enter fullscreen mode Exit fullscreen mode

Slice creates a shallow copy of the array [PROOF]

Any Object in Javascript can be copied by two ways: shallow copy and deep copy.
In Javascript, arrays and functions are also treated as Objects.

A shallow copy of an object is a copy whose properties share the same references as those of the source object from which the copy was made. Hence when you change the content of copied object then it also reflects the original one.

Shallow copy is irrelevent for arrays having only primitive values (like: number, string, boolean, null, undefined, symbol and bigInt), because these primitives are saved in call stack rather than memory heap (where reference types are stored).
For example:

let arr = [1,2,3,4,5]

let arrCopy = arr.slice()
arrCopy[0]=4

console.log(arrCopy) // [ 4, 2, 3, 4, 5]
console.log(arr)     // [ 1, 2, 3, 4, 5]

Enter fullscreen mode Exit fullscreen mode

Here you can see that even we changed the content of the copied array, but it is not reflected in the original one. Because the elements inside the array are primitives (here, numbers).

Now,

let arr = [ [1] ,2,3,4,5]

let arrCopy = arr.slice()
arrCopy[0][0]=4

console.log(arrCopy) // [ [ 4 ], 2, 3, 4, 5]
console.log(arr)     // [ [ 4 ], 2, 3, 4, 5]

Enter fullscreen mode Exit fullscreen mode

Here, you can clearly see that changing the copied array do reflects the original one, because this time the change is done in array and array is a reference type.



Bonus: Different ways to get the last item of an array
let arr = [1,2,3,4,5,6]
console.log( arr[arr.length-1] ) // 6
console.log( arr.at(-1) )        // 6
console.log( arr.slice(-1)[0] )  // 6

Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
desoga profile image
deji adesoga

I would suggest post title should be, A quick breakdown of the slice() Method in JavaScript. Helps with SEO.

Collapse
 
merudra754 profile image
Rudra Pratap

Thank you for your suggestion :)

Collapse
 
desoga profile image
deji adesoga

You're welcome, brother.

Collapse
 
tolgahanbeyazoglu profile image
tolgahan beyazoğlu

good

Collapse
 
merudra754 profile image
Rudra Pratap

Thank you :)