Skip to main content

Command Palette

Search for a command to run...

Slice in JavaScript

Published
2 min read
Slice in JavaScript
S

I am Senior Frontend Engineer and post daily tips about Web Dev

My goal is to encourage more people to get into tech.

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