CodingNeed.

2 · Model and build · 8 MIN

Keep a type relationship

Arrays store values in order, starting at index zero.

A generic preserves a relationship between an input type and output type. T[] contains T values, so first returns T or null for an empty list.

A row of numbered lockers starts at locker 0 in JavaScript.

Read the example

function first<T>(items: T[]): T | null {
  return items.length ? items[0] : null;
}
console.log(first([2, 4]));
Check the expected output
2

Your challenge

Return the first item of the input array. Return null if the array is empty.

Common trap

The last index is length - 1, not length.

Next lesson: Project · Typed expense summary →

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.