How to get the first n items in an array in JS

By

Learn how to get the first n items of a JavaScript array using the built-in slice() method, passing 0 and n, without modifying the original array.

~~~

Given a JavaScript array, you get the first n items by calling the built-in slice() method, passing 0 as the start and n as the end.

I use this all the time. Show the top 5 results of a search, take the 3 most recent posts, preview the first few rows of a dataset.

const arrayToCut = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

const n = 5 //get the first 5 items

const newArray = arrayToCut.slice(0, n)
//[1, 2, 3, 4, 5]

slice() copies the items from the start index up to, but not including, the end index. That’s why slice(0, 5) gives you exactly 5 items.

Note that the original array is not modified in this operation. slice() returns a brand new array, and arrayToCut keeps all 10 items.

What if n is bigger than the array?

Nothing bad happens. slice() just stops at the end of the array:

const scores = [82, 91, 76]
scores.slice(0, 10)
//[82, 91, 76]

No error, no undefined entries. You get as many items as exist. This makes slice() safe to use when you don’t know the array length in advance, like with API responses.

If you pass 0 as both arguments, you get an empty array back:

scores.slice(0, 0) //[]

Don’t confuse slice() with splice()

Here’s the classic pitfall. JavaScript also has a splice() method, with a nearly identical name, and it does something very different. splice() removes items from the original array, mutating it in place:

const scores = [82, 91, 76, 88]
scores.splice(0, 2)
//scores is now [76, 88]

If you reach for splice() when you meant slice(), your original array silently loses items. I’ve seen this bug ship to production more than once. If you only want to read the first n items, slice() is the one you want.

One more thing. For just the first item, skip the method call and use the index directly:

const posts = ['intro to git', 'css grid', 'node streams']
posts[0] //'intro to git'

For anything more than one item, slice(0, n) is the way.

~~~

Related posts about js: