Skip to main content

head()

head<T>(array): T | undefined

Gets the first element of array.

Alias for first.

DEPRECATED

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

Reason:
Alias of first


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 (Remeda, Radashi) ยท head (Lodash, es-toolkit, Ramda, Effect) ยท โŒ (Modern Dash)


Exampleโ€‹

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

// โŒ Deprecated approach
const firstElement = head(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. Deprecated: Use array[0] or array.at(0) directly.

Empty Arrayโ€‹

Native Equivalentโ€‹

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

Use Casesโ€‹

Get first element ๐Ÿ“Œโ€‹

Get the first element of an array.

const items = [1, 2, 3, 4];
items[0];
// => 1

Get element at positionโ€‹

Access element at a specific index.

const items = ["a", "b", "c", "d"];
items[2];
// => "c"

Get element from endโ€‹

Access elements from the end using negative index.

const items = [1, 2, 3, 4, 5];
items.at(-2);
// => 4