Programming
Arrays
Code Tutorial
Javascript
Data Structures

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.

javascript
1const colors = ["red", "green", "blue", "yellow", "purple"];
2const firstThree = colors.slice(0, 3);
3
4console.log(firstThree); // ["red", "green", "blue"]
5console.log(colors);     // ["red", "green", "blue", "yellow", "purple"] (unchanged)

When N exceeds the array length

slice returns whatever elements exist, so you usually do not need a bounds check first.

javascript
const items = [1, 2, 3];
console.log(items.slice(0, 100)); // [1, 2, 3]

When N is zero or negative

javascript
1const items = [1, 2, 3, 4, 5];
2
3console.log(items.slice(0, 0));   // []
4console.log(items.slice(0, -1));  // [1, 2, 3, 4] (negative end counts from the end)

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.

MethodMutates OriginalReturnsUse Case
slice(0, n)NoNew array with first N elementsRead a prefix without changing the source
splice(0, n)YesArray of removed elementsRemove and consume the first N elements
javascript
1// slice: non-destructive
2const a = [10, 20, 30, 40, 50];
3const sliced = a.slice(0, 3);
4console.log(sliced); // [10, 20, 30]
5console.log(a);      // [10, 20, 30, 40, 50] (unchanged)
6
7// splice: destructive
8const b = [10, 20, 30, 40, 50];
9const spliced = b.splice(0, 3);
10console.log(spliced); // [10, 20, 30]
11console.log(b);       // [40, 50] (mutated!)

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:

javascript
1function takeFirst(arr, n) {
2  if (!Array.isArray(arr)) {
3    throw new TypeError("Expected an array");
4  }
5  const count = Math.max(0, Math.floor(n));
6  return arr.slice(0, count);
7}
8
9console.log(takeFirst([1, 2, 3, 4, 5], 3));    // [1, 2, 3]
10console.log(takeFirst([1, 2, 3], 10));           // [1, 2, 3]
11console.log(takeFirst([1, 2, 3, 4, 5], -2));     // []
12console.log(takeFirst([1, 2, 3, 4, 5], 2.7));    // [1, 2]

The helper clamps negative values to 0 and floors fractional numbers, so the boundary behavior is explicit.

TypeScript version

typescript
1function takeFirst<T>(arr: T[], n: number): T[] {
2  const count = Math.max(0, Math.floor(n));
3  return arr.slice(0, count);
4}
5
6const users: string[] = ["Alice", "Bob", "Charlie", "Diana"];
7const topTwo: string[] = takeFirst(users, 2); // ["Alice", "Bob"]

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.

python
1values = [10, 20, 30, 40, 50]
2first_three = values[:3]
3print(first_three)  # [10, 20, 30]
4print(values)       # [10, 20, 30, 40, 50] (unchanged)
5
6# N larger than length
7print(values[:100])  # [10, 20, 30, 40, 50]

Java

Java arrays are fixed-size, so taking a prefix creates a new array.

java
1import java.util.Arrays;
2
3public class Main {
4    public static void main(String[] args) {
5        int[] values = {10, 20, 30, 40, 50};
6        int n = 3;
7
8        int[] firstN = Arrays.copyOfRange(values, 0, Math.min(n, values.length));
9        System.out.println(Arrays.toString(firstN)); // [10, 20, 30]
10    }
11}

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:

java
1import java.util.List;
2
3List<String> names = List.of("Alice", "Bob", "Charlie", "Diana");
4List<String> firstTwo = names.subList(0, Math.min(2, names.size()));
5// ["Alice", "Bob"]

subList returns a view, not a copy. Changes to the original list show up in the sublist.

C++

cpp
1#include <vector>
2#include <algorithm>
3#include <iostream>
4
5int main() {
6    std::vector<int> values = {10, 20, 30, 40, 50};
7    int n = 3;
8
9    std::vector<int> firstN(values.begin(), values.begin() + std::min(n, (int)values.size()));
10
11    for (int v : firstN) {
12        std::cout << v << " ";  // 10 20 30
13    }
14    return 0;
15}

The iterator-range constructor copies the elements into a new vector. std::min prevents advancing the iterator past the end.

Syntax by language

LanguageSyntaxMutates OriginalHandles N > Length
JavaScriptarr.slice(0, n)NoYes, returns all elements
Pythonarr[:n]NoYes, returns all elements
Java (array)Arrays.copyOfRange(arr, 0, n)NoPads 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)NoUndefined behavior if n > size (use std::min)
TypeScriptarr.slice(0, n)NoYes, 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.

javascript
1const original = [{ name: "Alice" }, { name: "Bob" }];
2const first = original.slice(0, 1);
3
4first[0].name = "Modified";
5console.log(original[0].name); // "Modified" (same reference)

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:

javascript
1const largeArray = new Array(1_000_000).fill(0).map((_, i) => i);
2
3// Creates a 1000-element copy
4const firstThousand = largeArray.slice(0, 1000);
5
6// Alternative: iterate without copying
7for (let i = 0; i < 1000 && i < largeArray.length; i++) {
8  process(largeArray[i]);
9}

Mistakes to avoid

  • Using splice instead of slice. It mutates the original array, which breaks frameworks like React or Redux where state should be immutable.
  • Treating the second argument to slice as 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 slice deep-copies objects. Mutating an object in the sliced array also mutates it in the original.
  • Using Arrays.copyOfRange in Java without bounds checking. An end index past the length silently pads the copy with default values (0 or null).
  • Treating a Java subList as independent. It is a view backed by the original list, and structural changes to the original invalidate it.

Course
Intermediate
27 lessons
15 hours
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 course
Data 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.

Practice algorithms