Skip to main content

first()

first<T>(array): T | undefined

Gets the first element of array.

DEPRECATED

Use array[0] or array.at(0) directly instead.

Reason:
Native equivalent method now available


Type Parametersโ€‹

T: Tโ€‹

The type of elements in the array.


Parametersโ€‹

array: T[]โ€‹

The array to query.


Returns: T | undefinedโ€‹

The first element of the array, or undefined if empty.


See Alsoโ€‹


Sinceโ€‹

2.0.0


Also known asโ€‹

at(arr, 0) (Antfu) ยท first (Lodash, Remeda, Radashi) ยท head (es-toolkit, Ramda, Effect) ยท โŒ (Modern Dash)


Exampleโ€‹

const numbers = [1, 2, 3, 4, 5];

// โŒ Deprecated approach
const firstElement = first(numbers);
console.log(firstElement); // 1

// โœ… Recommended approach
const firstNative = numbers[0];
console.log(firstNative); // 1

// โœ… Modern approach with ES2022
const firstModern = numbers.at(0);
console.log(firstModern); // 1

How it works?โ€‹

Gets the first element of an array. Alias for head. Deprecated: Use array[0] or array.at(0) directly.

Native Equivalentโ€‹

// โŒ first(arr)
// โœ… arr[0]
// โœ… arr.at(0) // ES2022

Use Casesโ€‹

Get default selection from lists ๐Ÿ“Œโ€‹

Retrieve the first element as the default selected item.

const countries = ["United States", "Canada", "Mexico"];
countries[0];
// => "United States"

Get the top/most relevant result from a search response.

const searchResults = [{ title: "Best Match", score: 0.98 }, ...];
searchResults[0];
// => { title: "Best Match", score: 0.98 }

Get primary validation errorโ€‹

Extract the first validation error to display.

const errors = [{ field: "email", message: "Invalid" }, ...];
errors[0];
// => { field: "email", message: "Invalid" }