How to get the first N elements of an array in JavaScript
Codemia Knowledge Hub ·
In JavaScript, array.slice(0, n) returns a new array with the first N elements and leaves the original unchanged. If N is larger than the array length, slice returns every element without throwing. Every mainstream language has an equivalent, shown further down.
slice in JavaScript
Array.prototype.slice(start, end) copies a section of an array into a new array. start is inclusive and end is exclusive.
When N exceeds the array length
slice returns whatever elements exist, so you usually do not need a bounds check first.
When N is zero or negative
A negative end does not mean "the first negative N elements". It means "stop that many positions from the end", which surprises anyone who expected an empty result.
slice vs splice
The names are almost identical, but the behavior is not.
| Method | Mutates Original | Returns | Use Case |
slice(0, n) | No | New array with first N elements | Read a prefix without changing the source |
splice(0, n) | Yes | Array of removed elements | Remove and consume the first N elements |
If the array is shared across functions or stored in a state container like Redux, using splice where you meant slice creates a mutation bug that is hard to trace.
A reusable takeFirst helper
When the operation shows up repeatedly, a named function states the intent better than inline slice calls:
The helper clamps negative values to 0 and floors fractional numbers, so the boundary behavior is explicit.
TypeScript version
The generic keeps the element type through the call, so the return type stays string[] instead of collapsing to any[].
First N elements in other languages
Python
Slice syntax is concise and tolerates out-of-range bounds.
Java
Java arrays are fixed-size, so taking a prefix creates a new array.
Unlike JavaScript's slice, Arrays.copyOfRange does not stop at the end of the array: if the end index exceeds the length, the copy is padded with default values (zeros for int[]). The Math.min guard keeps the result to the real elements.
For List types, use subList:
subList returns a view, not a copy. Changes to the original list show up in the sublist.
C++
The iterator-range constructor copies the elements into a new vector. std::min prevents advancing the iterator past the end.
Syntax by language
| Language | Syntax | Mutates Original | Handles N > Length |
| JavaScript | arr.slice(0, n) | No | Yes, returns all elements |
| Python | arr[:n] | No | Yes, returns all elements |
| Java (array) | Arrays.copyOfRange(arr, 0, n) | No | Pads with default values if n > length (use Math.min) |
| Java (List) | list.subList(0, n) | Returns a view (not independent) | Throws if n > size (use Math.min) |
| C++ | vector(begin, begin + n) | No | Undefined behavior if n > size (use std::min) |
| TypeScript | arr.slice(0, n) | No | Yes, returns all elements |
Shallow copies and large arrays
slice makes a shallow copy. For primitives, that is a copy proportional to N. For objects, the new array holds references to the same objects.
If you need independent objects, deep-clone them separately.
For very large arrays where you only need to iterate over the first N elements, not store them, a plain loop avoids creating a new array:
Mistakes to avoid
- Using
spliceinstead ofslice. It mutates the original array, which breaks frameworks like React or Redux where state should be immutable. - Treating the second argument to
sliceas a count. It is an exclusive end index. With a start of 0 the two coincide, but not for other start indices. - Not handling negative N.
slice(0, -3)returns everything except the last 3, rarely what a caller passing a negative "first N" wanted. - Assuming
slicedeep-copies objects. Mutating an object in the sliced array also mutates it in the original. - Using
Arrays.copyOfRangein Java without bounds checking. An end index past the length silently pads the copy with default values (0 or null). - Treating a Java
subListas independent. It is a view backed by the original list, and structural changes to the original invalidate it.
Related reading
- How to get first object out from ListObject using Linq
- How to get indices of a sorted array in Python
- How to get IntPtr from byte in C
- How to get largest number of consecutive integers in a substantially large array (spread across multiple machines)
- How to get GET (query string) variables in Express.js on Node.js?
- How to Get Signed S3 Url in AWS-SDK JS Version 3?
- How to get last items of a list in Python?
- how to get longest repeating string in substring from suffix tree
System design interview problems on this topic
- Design Google Doc: solution and walkthrough
- Design Facebook Messenger: solution and walkthrough
- Design Typeahead Suggestion: solution and walkthrough
- Design an Online Presence Indicator Service: solution and walkthrough

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.