Slice in JavaScript

Slice in JavaScript

ยท

2 min read

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

Syntax:

arr.slice([start[, end]])

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

In end, slice extracts up but not including end.

It's too theoretically right ๐Ÿคฃ Let's checkout few examples ๐Ÿ‘‡

Using two arguments โœ…

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

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

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

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); // ["๐Ÿ‡",  "๐Ÿ’"]

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); // ["๐ŸŒฝ"]

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); // []

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); // ["๐Ÿ“",  "๐ŸŒฝ",  "๐Ÿ‡",  "๐Ÿ’"]

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

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

Note: ๐Ÿงจ

Slice is immutable and Splice mutates the array.

To Understand more about Splice, Checkout this Article .

Reference ๐Ÿง

Slice MDN


Thanks for reading the article โค๏ธ

Buy Me A Coffee

๐ŸŒŸ Twitter ๐Ÿ“š Ebooks ๐ŸŒŸ Instagram

Did you find this article valuable?

Support Suprabha Supi by becoming a sponsor. Any amount is appreciated!