DEV Community

Cover image for Slice in JavaScript
Suprabha
Suprabha

Posted on

Slice in JavaScript

The slice method returns a new array with a copied slice from the original array.

Syntax:

arr.slice([start[, end]])
Enter fullscreen mode Exit fullscreen mode

start refers Zero-based index. If start is undefined, slice starts from the index 0.

In end, slice extracts up to but not including end.

Its too theoretically right ๐Ÿ˜œ, lets understand by few examples.

Using two arguments โœ…:

const arr = ['๐Ÿ', '๐Ÿ“', '๐ŸŒฝ', '๐Ÿ‡', '๐Ÿ’'];
const newArr = arr.slice(2,4);
console.log(newArr); // ["๐ŸŒฝ", "๐Ÿ‡"]
Enter fullscreen mode Exit fullscreen mode

Without arguments, you get a copy of the full array โœ…

const arr = ['๐Ÿ', '๐Ÿ“', '๐ŸŒฝ', '๐Ÿ‡', '๐Ÿ’'];
const newArr = arr.slice();
console.log(newArr); // ["๐Ÿ", "๐Ÿ“", "๐ŸŒฝ", "๐Ÿ‡", "๐Ÿ’"]
Enter fullscreen mode Exit fullscreen mode

Using one argument, you get a copy from the specified index to the end of the array โœ…

const arr = ['๐Ÿ', '๐Ÿ“', '๐ŸŒฝ', '๐Ÿ‡', '๐Ÿ’'];
const newArr = arr.slice(3);
console.log(newArr); // ["๐Ÿ‡", "๐Ÿ’"]
Enter fullscreen mode Exit fullscreen mode

Index can also be negative, in which case the starting index is calculated from the end โœ…

const arr = ['๐Ÿ', '๐Ÿ“', '๐ŸŒฝ', '๐Ÿ‡', '๐Ÿ’'];
const newArr = arr.slice(2,-2);
console.log(newArr); // ["๐ŸŒฝ"]
Enter fullscreen mode Exit fullscreen mode

If start is greater than the index range of the sequence, an empty array is returned โœ…

const arr = ['๐Ÿ', '๐Ÿ“', '๐ŸŒฝ', '๐Ÿ‡', '๐Ÿ’'];
const newArr = arr.slice(6);
console.log(newArr); // []
Enter fullscreen mode Exit fullscreen mode

If end is greater than the length of the sequence, slice extracts through to the end of the sequence โœ…

const arr = ['๐Ÿ', '๐Ÿ“', '๐ŸŒฝ', '๐Ÿ‡', '๐Ÿ’'];
const newArr = arr.slice(1,9);
console.log(newArr); // ["๐Ÿ“", "๐ŸŒฝ", "๐Ÿ‡", "๐Ÿ’"]
Enter fullscreen mode Exit fullscreen mode

slice() method can also be used for strings โœ…

const arr = 'suprabha';
const newArr = arr.slice(0,3);
console.log(newArr); // "sup"
Enter fullscreen mode Exit fullscreen mode

Note: ๐Ÿงจ

Slice is immutable and Splice mutates the array.

Reference ๐Ÿง

Slice MDN

๐ŸŒŸ Twitter ๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป Suprabha.me ๐ŸŒŸ Instagram

Top comments (4)

Collapse
 
functional_js profile image
Functional Javascript

Nice refresher Suprabha.

Here are two lists that people may find useful:

mutator array methods:

push (back add)
pop (back remove)
unshift (front add)
shift (front remove)
splice
sort
reverse
fill
forEach

non-mutator array methods:

concat
join
filter
slice
map
reduce
find
findIndex
some
every
includes
flat
flatMap

Collapse
 
suprabhasupi profile image
Suprabha

Hahaha I can understand. I fixed that ๐Ÿคช

Collapse
 
iamashusahoo profile image
Ashutosh

Very nicely explained

Collapse
 
suprabhasupi profile image
Suprabha

I tried to join, but wouldn't able to join to the group.