How to Get The First Items of an Array With JavaScript

How do you access the first X number of elements in a JavaScript array? You use JavaScript’s built-in slice() method.

As an example, let’s say you need to manipulate the first 3 items of an array. In this case the array is a list of exercises:

const exerciseList = [
  "Deadlift",
  "Squat",
  "Push-up",
  "Pull-up",
  "Turkish Get-up",
  "Kettlebell Swing",
]

First we define the number of items we want to access:

// get the first 3 items
const numberOfItems = 3

Then we declare a new variable to contain a reference to the first 3 items:

const firstThreeExercises = exerciseList.slice(0, numberOfItems)

Try to print the value of exerciseList and firstThreeExercises using console.log():

console.log(exerciseList)
// Output: ["Deadlift", "Squat", "Push-up", "Pull-up", "Turkish Get-up", "Kettlebell Swing"]

console.log(firstThreeExercises)
// Output ["Deadlift", "Squat", "Push-up"]

Note: the original exerciseList array is not modified with this approach.


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on