DEV Community

Discussion on: `at` coming soon to ECMAScript

Collapse
 
tiguchi profile image
Thomas Werner

I would also expect an exception to happen instead. Passing in an out of bounds index argument should be considered a misuse of the method and raise an error instead. The return result of undefined is not sufficient for detecting if the index is out of bounds, since that accessed element could be undefined.

In programming it's better to fail early, so come a crash and the time to debug, the failing line of code in the stacktrace is as close as possible to the root of the problem.

Ideally the language and API should make it harder to misuse it, but in JavaScript a lot of nonsensical things are possible that can cause hard to debug problems because cause and effect can be delayed. That forces us to come up with ways to make it stricter such as using static type checkers or switching to a different cross-compiled language altogether.

This could have been an opportunity for getting it right though 😞

Compatibility and interchangeability with the existing bracket syntax was probably not the reason behind that design decision. The at function expects an integer index argument. The official polyfill reference implementation converts non-numeric or fractional numbers to whole numbers, which is another strike in my book.

The method should simply reject non-numeric, non-integer arguments. Instead we end up with the following possibility that doesn't make sense to me either: a[1.1] !== a.at(1.1). Fractional numbers should cause a crash too. Why second-guess the programmer and try to auto-correct them based on assumptions? 🤷