32

I know how to index an array with [] but I'm trying to display an item from an array based on its index using Array.at() method as described here MDN Docs - Array.at

But I get the following error:

Uncaught TypeError: arr1.at is not a function

I double-checked it, and everything is ok, however I don't know what's going wrong.

Here is my code:

const arr1 = [10, 20, 30, 40, 50];

const res = arr1.at(2);
console.log(res);

Note: This is different than the proposed duplicate of How to get value at a specific index of array In JavaScript?. That question is about methods for accessing an array, this question is why a new API for doing so is unavailable and how to rectify that.

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Safin Ghoghabori
  • 516
  • 1
  • 6
  • 17
  • There is no function `at` on arrays. Try array index instead i.e. `arr1[2]` – DecPK Jul 21 '21 at 04:47
  • 7
    @decpk first of all why you directly devoted this question? Please don't do that and demotivate beginners. Moreover its exist you can check here "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at" – Safin Ghoghabori Jul 21 '21 at 04:50
  • 11
    @safinghoghabori evidently `.at()` doesn't exist in your environment. You *are* getting an error. `.at()` is extremenly new - it's still [a proposal](https://github.com/tc39/proposal-relative-indexing-method) (Stage 3), not even added to [the latest draft of the ES specs](https://tc39.es/ecma262/#sec-properties-of-the-array-prototype-object). So, environments that support it are ***very*** few. You can see the table at the bottom of the page. – VLAZ Jul 21 '21 at 04:53
  • yes maybe but i was referring MDN docs and I encounter that method – Safin Ghoghabori Jul 21 '21 at 06:06
  • @VLAZ that looks like it could be an answer. – cigien Aug 11 '21 at 23:56
  • 3
    At is better for accessing the last value - It's coming soon - https://tc39.es/ecma262/#sec-array.prototype.at – Manohar Reddy Poreddy Sep 10 '21 at 02:58
  • 1
    @CertainPerformance, please re-review. This question is not a dupe of the listed question – KyleMit Jan 02 '22 at 15:07
  • 2
    @SafinGhoghabori Yes, you are referencing the docs. But did you also check the browser compatiblitity table? It says for instance Chrome >= 92 or nodeJs >= 16.6. Does your environment meet this requirement? Probably not ... – derpirscher Jan 02 '22 at 15:18
  • Closely related: [Property "at" does not exist on Array](https://stackoverflow.com/q/69869479/1048572) in TypeScript, and [Downsides of using `array.at(index)`](https://stackoverflow.com/q/70456996/1048572) – Bergi Jan 02 '22 at 15:22
  • I only found this error on Safari – Marco Mazzon Jan 22 '22 at 16:55
  • We have a CI test pipeline that uses node 14.x and it just so seems that it should be 16.6.x+ See answers below – O-9 Dec 28 '22 at 09:44

5 Answers5

18

If you get this message, whatever platform you're running the code on does not support the method yet. It's quite new - while the most recent versions of most browsers support it, anything before 2021 definitely won't. This method was only very recently signed off on (end of August 2021) and incorporated into the official specification, so it won't exist in older environments. Either upgrade your environment, or add a polyfill.

Per the proposal document, a "rough polyfill" that should be standards-compliant for most cases is:

function at(n) {
    // ToInteger() abstract op
    n = Math.trunc(n) || 0;
    // Allow negative indexing from the end
    if (n < 0) n += this.length;
    // OOB access is guaranteed to return undefined
    if (n < 0 || n >= this.length) return undefined;
    // Otherwise, this is just normal property access
    return this[n];
}

const TypedArray = Reflect.getPrototypeOf(Int8Array);
for (const C of [Array, String, TypedArray]) {
    Object.defineProperty(C.prototype, "at",
                          { value: at,
                            writable: true,
                            enumerable: false,
                            configurable: true });
}

Simply run that before trying to use .at, and you should be able to use it, even on older incompatible environments. You can also install this more exhaustive shim instead if you wish.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
7

If you're using node.js then please check the version of node.

It should be greater than 16.6.0. If not then update the node.js version.

Browser compatibility of Array.prototype.at()

enter image description here

li ki
  • 342
  • 3
  • 11
Vikram Sapate
  • 1,087
  • 1
  • 11
  • 16
6

One option is to use the core-js library...

Modular standard library for JavaScript. Includes polyfills for ECMAScript up to 2021: promises, symbols, collections, iterators, typed arrays, many other features, ECMAScript proposals, some cross-platform WHATWG / W3C features and proposals like URL. You can load only required features or use it without global namespace pollution.

First install it with npm or yarn:

npm install core-js

or

yarn add core-js

Then use it in your JS or TS project like this:

import 'core-js/features/array/at';

let arr = [];
arr.push(42);
console.log(arr.at(0));

Note that the code above only imports the at method for array. To import all polyfills or a subset:

// polyfill all `core-js` features, including early-stage proposals:
import "core-js";
// or:
import "core-js/features";
// polyfill all actual features - stable ES, web standards and stage 3 ES proposals:
import "core-js/actual";
// polyfill only stable features - ES and web standards:
import "core-js/stable";
// polyfill only stable ES features:
import "core-js/es";
Bjørnar Hvidsten
  • 859
  • 12
  • 15
0

The code is working fine in Stackoverflow code terminal. Your machine might not support the same due to JS versioning. The method is introduced recently.

enter image description here

Ritik Banger
  • 2,107
  • 5
  • 25
0

I ran into this same issue when using Pipedream. I didn't realize that at() wasn't included in the NodeJS version they're using hinted at by Li Ki.

I implemented a similar solution proposed by Bjørnar Hvidsten; however, to get it to work in Pipedream, I simply added the following to the top of my NodeJS code.

import 'core-js'
const myArray = [1,2,3]

console.log(typeof myArray.at) // "function"

P.S. Referencing specific parts of core-js resulted in errors inside Pipedream, at least how I was trying to call it.

AnonymousSB
  • 3,516
  • 10
  • 28