Arrays allow you to store multiple elements in a single object, and each element can be accessed using its index.
You can get the first N elements of an array in JavaScript using myArray.slice(0, n) statement.
Basic Example
var myArray = ["owl", "parrot", "dove"];
var firstNElements = myArray.slice(0, 2);
console.log(firstNElements); // ["owl", "parrot"]
This tutorial teaches you the different methods to get the first n elements of an array in JavaScript and when it is appropriate to use each method.
Using Slice
The slice() method returns a new array with a shallow copy of a portion of an existing array.
It will NOT mutate the original array. A new array will be created instead.
To get the first n
elements of an array using the slice()
method,
- Invoke the
slice()
method in the array. - Pass the
start
index0
to start getting the elements from the first position - Pass the
end
indexn
to get the first n elements - If the
end
index is more than the array’s length, an error will not be thrown. Instead, all the items of the array will be returned.
Use this method when you want to create a new array with the first n
elements of the existing array.
Code
The following code demonstrates how to get the first two elements of the array.
var myArray = ["owl", "parrot", "dove"];
var firstNElements = myArray.slice(0, 2);
console.log(firstNElements); // ["owl", "parrot"]
Using Splice
The splice() method changes the existing array by removing or replacing the existing items of the array.
It mutates the original array. This means, only the selected elements will be retained in the array, and other elements will be removed.
To select the first n
elements of an existing array using the splice()
method,
- Invoke the
splice()
method on the existing array - Pass the
n
value to select the firstn
elements of the array
Use this method when you want to retain the first n
elements in the existing array and remove the other elements from the array. In other words, modify the existing array instead of creating a new array with the first n
elements.
Code
var myArray = ["owl", "parrot", "dove"];
myArray.splice(2);
console.log(myArray); // ["owl", "parrot"]
Using Destructuring
The destructuring assignment syntax unpacks the values from the array into distinct variables.
To get the first n elements of an array using the destructuring technique,
- Create an
n
number of variables and assign the array to those variables - The first
n
items from the array will be assigned to each variable in the list
Use this method when you want to assign the first n
number of elements into distinct variables instead of storing them in a single array object.
Code
var myArray = ["owl", "parrot", "dove"];
var [first, second] = myArray;
console.log(first, second); // "owl", "parrot"