Clean Markup

Cleaner Collection Access in JavaScript with Array at and Object hasOwn

Cleaner Collection Access in JavaScript with Array at and Object hasOwn

JavaScript has historically lacked simple ergonomic primitives found in Python and Ruby—most notably, concise negative index lookups for accessing the last item of an array, and a bulletproof way to verify an object's own properties without risking prototype shadowing.

ES2022 introduced two standard methods that simplify daily collection operations: Array.prototype.at() and Object.hasOwn().

Example

const items = ['first', 'second', 'third', 'last'];

// Old awkward lookup:
const lastOld = items[items.length - 1];

// Clean ES2022 lookup:
const lastNew = items.at(-1); // "last"
const secondToLast = items.at(-2); // "third"

Implementation

Object.hasOwn() provides a safe alternative to Object.prototype.hasOwnProperty.call():

// Safely inspect dictionary objects created with Object.create(null)
const dict = Object.create(null);
dict.key = 'value';

// dict.hasOwnProperty('key') throws TypeError!
console.log(Object.hasOwn(dict, 'key')); // true

Main Point: Use array.at(-1) for clean negative index lookups and Object.hasOwn(obj, prop) for safe, prototype-resistant property validation.

Credits

Photo by Luca Bravo on Unsplash

← Home