Back to Snippets
CODE

Safe Array Item Access

Description

Prevents index out-of-bounds errors when accessing array elements, returns default value for invalid indices

Code

/**
 * Safe array item access (prevents out-of-bounds errors)
 * @param arr Target array
 * @param index Target index
 * @param defaultValue Default value for invalid indices
 * @returns Value at index or default value
 */
function getArrayItem<T>(arr: T[], index: number, defaultValue: T): T {
  return index >= 0 && index < arr.length ? arr[index] : defaultValue;
}

// Usage Example
console.log(getArrayItem([1, 2, 3], 5, 0)); // 0
console.log(getArrayItem([1, 2, 3], 1, 0)); // 2

Usage

Essential for accessing array elements with uncertain indices (e.g., dynamic data, user input-based indexing)

Tags

Array ManipulationError PreventionSafe Access