How to get first N number of elements from an array
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
In JavaScript, use array.slice(0, n) to get the first N elements from an array. It returns a new array containing the first N items without modifying the original. If N is larger than the array length, slice returns all available elements without throwing an error. This operation is one of the most common array manipulations, and every mainstream language has an equivalent.
Using slice in JavaScript
Array.prototype.slice(start, end) extracts a section of an array and returns it as a new array. The start index is inclusive and the end index is exclusive.
When N Exceeds Array Length
slice does not throw an error. It returns whatever elements are available.
This means you typically do not need a bounds check before calling slice. The method handles it internally.
When N Is Zero or Negative
A negative end argument does not mean "first negative-N elements." It means "stop that many positions from the end." This is sometimes useful but often surprising if you expected an empty result.
slice vs splice: A Critical Difference
These two methods have almost identical names but fundamentally different behaviors.
| 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 your array is shared across multiple functions or stored in a state management system like Redux, using splice when you meant slice creates a mutation bug that can be difficult to trace.
Writing a Reusable Helper
When this operation appears repeatedly in application code, wrapping it in a named function communicates intent more clearly than inline slice calls.
This helper clamps negative values to 0 and floors floating-point numbers, making the boundary behavior explicit.
TypeScript Version
Generics preserve the element type through the function call, so the return type stays string[] rather than collapsing to any[].
Equivalent Operations in Other Languages
Python
Python's slice syntax is concise and handles out-of-bounds gracefully.
Java
Java arrays are fixed-size, so prefix extraction creates a new array.
Unlike JavaScript's slice, Arrays.copyOfRange throws ArrayIndexOutOfBoundsException if the end index exceeds the array length. The Math.min guard is necessary.
For List types, Java offers subList:
Note that subList returns a view, not a copy. Modifications to the original list affect the sublist.
C++
The iterator-range constructor copies elements into a new vector. The std::min prevents advancing the iterator past the end.
Comparison Table
| 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 | Throws 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 |
Performance Considerations
slice creates a shallow copy. For arrays of primitive values, this is a memory copy proportional to N. For arrays of objects, the new array holds references to the same objects, not deep copies.
If you need independent copies of the objects, you must deep-clone them separately. slice alone is not enough.
For very large arrays where you only need to iterate over the first N elements (not store them), consider a simple loop instead of creating a new array:
Common Pitfalls
- Using
spliceinstead ofslice. This mutates the original array. In state-driven frameworks like React or Redux, this causes bugs because state should be immutable. - Assuming the second argument to
sliceis a count. It is an exclusive end index, not a count. For a prefix starting at 0, the values happen to be the same, but for non-zero start indices they differ. - Not handling negative N. JavaScript's
slice(0, -3)returns all elements except the last 3, which is rarely the intent when someone passes a "first N" value that happens to be negative. - Assuming
slicedeep-copies objects. It creates a shallow copy. Mutating an object in the sliced array also mutates it in the original. - Using
Arrays.copyOfRangein Java without bounds checking. Unlike JavaScript, Java throws an exception when the end index exceeds the array length. - Calling
subListin Java and treating the result as independent. The returned list is a view backed by the original list. Structural modifications to the original list invalidate the sublist.
Summary
- In JavaScript,
array.slice(0, n)is the standard way to get the first N elements. It returns a new array and does not modify the original. splicelooks similar but mutates the array. Useslicefor reading,splicefor consuming and removing.- JavaScript and Python handle N > array length gracefully. Java and C++ require explicit bounds checking.
slicecreates a shallow copy. Object references in the new array still point to the same objects.- Wrap the operation in a named helper like
takeFirst()when the boundary behavior (negative N, floats) matters to your application logic.
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

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 courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.