ES2022 New Syntax: Array.at()

ES2022 New Syntax: Array.at()

Everything about ES2022 Array.prototype.at() and its weird features

Sunkanmi Fafowora
ยทMay 14, 2022ยท

2 min read

Table of contents

  • What is ES2022 at() Function and How does it Work?
  • Weird Outputs
  • Conclusion
  • References

What is ES2022 at() Function and How does it Work?

ES2022 (ECMA Script 2022) is being approved in July, and it'll be banging with some amazing new syntax and features. One of the new syntax coming to ES2022 is an array function called at(). This function operates on an array, and takes in a given index within the array and returns the value of the specified index, otherwise, it returns undefined, let's see an example below.

console.log([1, 2, 3, 4, 5].at(-1));
// returns 5


console.log([1, 2, 3, 4, 5].at(9));
// returns "undefined"

Pretty cool right? Yes, I know you're used to the square bracket notation, and there's nothing wrong with that, but when referencing the last element of the array, it's just easier to write [1, 2, 3, 4, 5].at(-1) than writing array[array.length - 1].

Weird Outputs

So I did a little test on this feature and found some weird bugs in JavaScript which is nothing new at this point.

Do you know that if you pass in an array into the at() function, it returns the first element? ๐Ÿ˜ And there're way more values I tried with it from strings to an empty array object, and the ๐Ÿ˜Ž emoji.

Just take a look at the two gifs below.

gif displaying js weird outputs

Oh, you think that's weird? Check out what it brings out when you pass in a string with the index inside. Yes, it returns the value of the index you specified. ๐Ÿ˜‚

gif displaying js weird outputs

In case you find more, do let me know in the comments section.

Conclusion

ES2022 will be approved and fully supported in July (check out Spec revisions and scheduling) as the ECMA TC39 committee (the committee responsible for evolving the ECMAScript programming language and authoring the specification) has reached the penultimate stage of ES2022 language specifications.

Even though there are still some weird findings with the JavaScript language (as always), I believe that the at() array function will be a very useful feature of the language once it's out and being used in multiple projects and applications.

Thank you for reading, and I hope you have a nice day ahead!

References

ย 
Share this