Read here. Code on desktop. The coding workspace opens on screens 1024px and wider.
JavaScript interview question
Array at
easy10 min
Read an array item by its position, supporting negative indices that count backwards from the end.
Requirements
Implement arrayAt(array, index = 0), the actual-array subset of Array.prototype.at. Keep this a standalone function; do not replace native methods.
Nonnegative indices count from the beginning; negative indices count from the end, so -1 selects the last item.
Truncate fractional indices towards zero. Treat NaN and an omitted or undefined index as 0. Infinite or out-of-bounds indices return undefined without reading that property.
Empty input and sparse slots return undefined. Return values by reference without mutating the array.
Assume actual arrays and numeric indices. Other index coercions, array-like objects, and subclasses/species are outside scope. Do not use the native at method.
Examples
Example 1
Input: arrayAt(['a', 'b', 'c'], 1)
Output: 'b'
Example 2
Input: arrayAt(['a', 'b', 'c'], -1)
Output: 'c'
Example 3
Input: arrayAt([1, 2], 5)
Output: undefined
Read positive or negative array positions.
What the tests check
Reads nonnegative indices
Counts negative indices from the end
Returns undefined outside either boundary
Returns undefined for empty arrays
Truncates fractional indices towards zero
Defaults omitted undefined and NaN indices to zero
Rejects infinite indices
Reads sparse slots as undefined and preserves falsy values
Leaves frozen input unchanged and preserves object identity