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"
Extract primary result from searchβ
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" }