0 of 5 problems solved0%
2 of 5

First or Default

Generic functions can keep array element types intact. If you return an element or a fallback of the same type parameter T, callers get the precise type back. Let inference do most of the work.

Use simple control flow. Avoid special cases for strings vs numbers—the type parameter will handle that.

function headOr<T>(xs: T[], d: T) {
  return xs.length ? xs[0] : d;
}

Your Task

Return the first element or a provided fallback.

  • Implement function firstOrDefault<T>(arr: T[], fallback: T): T.
  • Return arr[0] when the array is non-empty, otherwise return fallback.
  • Do not mutate the array.