Slice in JavaScript

Suprabha - Aug 22 '20 - - Dev Community

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
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .