JavaScript Glossary - Lesson #16

JavaScript Array .slice() Method

The slice array method copies a given part of an array returning the selected part as an array. It doesn’t mutate the given array rather, it returns a new array.

[1, 2, 3, 4, 5].slice(1)
// [2, 3, 4, 5]
// Array of various elements
const things = ['cup', 'house', 'spoon', 'plate']

// Copy array elements from index 1
const cutThings = things.slice(1)

// Output result
console.log(cutThings) // ["house","spoon","plate"]
array.slice(start, end)

start This is the start index for the slice selection. The slice will start from the element at the provided index. If just the start index is provided and no end index is provided, the returned array will contain elements from the start index to the end of the array - optional.

end This is the end index for selection. All the elements from the start index to the element before the end index are selected - optional

The method will return an array containing all the elements from the start index to the element before the end index. If no arguments are provided, it will return an array containing the elements in the parent array.

const numbers = [2, 3, 4, 5, 6];
const sliced = numbers.slice(2,4);

//output: Array [4,5]
//  An array of objects
const users = [{name: 'Pete', id: 1}, {name: 'Rich', id: 2}, {name: 'Johnny', id: 3}];

// Copy users from a particular index
const lastUsers = users.slice(1);

// Output users from the selected range
console.log(lastUsers); // [{"name":"Rich","id":2},{"name":"Johnny","id":3}]

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created which was acquired.


What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)