javascriptarrays

Why am I getting ".at" is not a function?


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.


Solution

  • 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.