Skip to the solution
EasyPhone Screen6 min read

What do Array.prototype.at() and String.prototype.at() do differently from bracket indexing, and why were they added?

278 views

The problem

Question presented to candidate: "What does .at() actually add on top of regular bracket indexing for arrays and strings, and why did the language add a whole new method just for this?"

What a strong answer should cover:

  • .at(index) accepts negative integers, counting back from the end: at(-1) is the last element, at(-2) is second-to-last, and so on.
  • Bracket notation does not support negative indices at all -- arr[-1] does not throw, it just looks up the property named "-1" on the array, which does not exist, so it returns undefined.
  • Both a valid negative index and an out-of-range index (too large positive, or too negative) return undefined for .at() with no throw.
  • at() is defined generically across indexable built-ins -- plain arrays, strings, and typed arrays all support it with the same semantics.
  • Motivation: before at(), getting the last element required arr[arr.length - 1], which recomputes/re-reads length and reads awkwardly, especially when arr itself is the result of a function call that would otherwise need to be invoked twice.

Clarifying questions expected:

  • "Should I also cover TypedArray.prototype.at(), or just Array and String?"
  • "Do you want me to compare this against .slice(-1)[0], which was the common pre-at() workaround?"

Code / implementation expected: Yes -- a runnable comparison of at() against bracket indexing for both positive and negative indices, including out-of-range behavior.

  • array
  • string
  • at-method

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read Β· 8 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptArray.prototype.at() and String.prototype.at() vs bracket indexing (run directly)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 32 of 165 in JavaScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Why would you add { passive: true } to a scroll or touchstart listener, and what problem does it solve for scroll performance?

Continue