How to Get the First 'n' Elements of a JavaScript Array?

To get the first 'n' elements of an array in JavaScript, you can simply use the Array.prototype.slice() method with 0 as the first argument and "n" (i.e. the number of elements you wish to extract) as the second argument. For example:

const arr = [ 1, 2, 3, 4, 5, 6 ];
const n = 3;
const newArr = arr.slice(0, n);

console.log(newArr); // [ 4, 5, 6 ]
console.log(arr); // [ 1, 2, 3, 4, 5, 6 ]

Please note that if you omit the second argument, or if the second argument is greater than the length of the sequence, slice() extracts through to the end of the sequence (i.e. it is equivalent to passing arr.length as the second argument).

As you can see from the code above, the original array is not modified. This is because the Array.prototype.slice() method returns a new array containing the extracted elements.

Also, it's worth mentioning that the Array.prototype.slice() method has great browser support across new and old browsers.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.