Hone logo
Hone
Problems

Accessing the First Element of a TypeScript Array

This challenge focuses on a fundamental array operation: retrieving the very first element. In programming, you'll frequently need to access specific items within a collection of data, and understanding how to get the initial one is a crucial building block.

Problem Description

Your task is to write a TypeScript function that takes an array as input and returns its first element.

Key Requirements:

  • The function should be named getFirstElement.
  • It must accept a single argument: an array. This array can contain elements of any type.
  • The function should return the element at index 0 of the input array.
  • If the input array is empty, the function should return undefined.

Expected Behavior:

  • For a non-empty array, return the element at the first position.
  • For an empty array, return undefined.

Edge Cases:

  • Handling of empty arrays is critical.

Examples

Example 1:

Input: [1, 2, 3, 4, 5]
Output: 1
Explanation: The first element of the array [1, 2, 3, 4, 5] is 1.

Example 2:

Input: ["apple", "banana", "cherry"]
Output: "apple"
Explanation: The first element of the array ["apple", "banana", "cherry"] is "apple".

Example 3:

Input: []
Output: undefined
Explanation: The input array is empty, so there is no first element to return.

Constraints

  • The input will always be an array.
  • The elements within the array can be of any valid TypeScript type (e.g., number, string, boolean, object, null, undefined).
  • The function should be efficient, with a time complexity of O(1) as accessing an array element by index is a constant time operation.

Notes

Consider how TypeScript's type system can help you define the function's signature clearly. Think about what the return type should be to accommodate both the presence of a first element and the case of an empty array. You do not need to implement error handling beyond returning undefined for empty arrays.

Loading editor...
typescript