arrayGet

arrayGet

> Functions

Returns the element of the list array at position index. If the index is outside the list, returns defaultValue instead. A negative index counts from the end: -1 is the last element.

Parameters
Return
TypeScript

In JavaScript, an out-of-bounds a[index] gives undefined: no error, but no fallback value either. Write a.at(index) ?? fallback to get the behavior of arrayGet — ?? only kicks in on null and undefined, whereas || would also override a legitimate 0 or empty string. a.at(index) accepts, like arrayGet, a negative index counted from the end, a.at(-1) being the last element, while a[-1] is always undefined.

Python

In Python, an out-of-bounds a[index] raises an IndexError instead of returning a fallback value, and a negative index counts from the end, as with arrayGet: a[-1] is the last element, not an error. To reproduce arrayGet(a, index, fallback): a[index] if -len(a) <= index < len(a) else fallback. On a dictionary, m.get(key, fallback) does exactly that.

Note