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

Learn how to extract the first 'n' items from an array in JavaScript

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.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.