Modern JS APIs: Object.hasOwn, toSorted & More

Everyone figured we'd keep patching JavaScript with lodash forever. These new APIs flip the script: immutable sorts, safe property checks, no more mutations sneaking into your React state.

JavaScript's Built-in Revolution: Safe Sorting, Immutable Updates, and Smarter Queries (Part 2) — theAIcatchup

Key Takeaways

  • Object.hasOwn eliminates hasOwnProperty's risks, enabling safe property checks everywhere.
  • toSorted, with(), findLast deliver immutable array ops natively — no more spread/map boilerplate.
  • URLSearchParams simplifies query handling, crushing fragile custom parsers.

Developers expected another round of polyfills or framework bandaids. Browsers shipping these APIs? That’s the plot twist — native tools that finally kill off brittle patterns, slashing bundle sizes and bugs in one swing.

Object.hasOwn. Two words. Total game-changer for property checks.

Here’s the thing: hasOwnProperty? It’s been a minefield since day one. Overridable. Crashes on null-prototype objects. Lies when some shady code overrides it. And yet, we’ve tolerated it for decades.

const obj = Object.create(null); obj.name = “Nagendra”; obj.hasOwnProperty(“name”); // ❌ TypeError: obj.hasOwnProperty is not a function

That snippet from the original post nails it. Boom — error city.

Object.hasOwn(obj, “key”) sidesteps all that. Works on anything. No overrides, no crashes. Filter own properties from prototypes effortlessly:

Why Object.hasOwn Ends the Property-Check Wars

Take inheritance-heavy codebases — think user objects extending base configs. Old way: Object.keys(user).filter(key => user.hasOwnProperty(key)). Messy, error-prone. New way: Object.hasOwn everywhere. Clean. Safe. Your API validators just got bulletproof.

But wait — React devs, imagine state validation without the paranoia. if (Object.hasOwn(apiResponse, “data”)) { render(it); }. No more “someone overrode hasOwnProperty” nightmares.

Adoption’s exploding. Chrome 110+, Firefox 112, Safari 15.4. Market share? Over 95% global coverage today. No excuses.

And here’s my take: this mirrors the jQuery cull a decade ago. Back then, native querySelector crushed $ selectors. Now, hasOwn buries duck-typed checks. Prediction: lodash’s isPlainObject usage drops 40% in six months.

Next up, arrays. Sorting without tears.

Does toSorted Finally Free Us from Spread Syntax Hell?

arr.sort() mutates. Always has. Spread copies? Wastes memory on big lists. Enter toSorted().

const leaderboard = players.toSorted((a, b) => b.score - a.score);

Original untouched. Perfect for React’s useState dance — no accidental re-renders from mutations.

toReversed() tags along. Flip [1,2,3] to [3,2,1] sans side effects. Why does this matter? State management libs like Zustand or even vanilla signals thrive on immutability. Mutations? Recipe for heisenbugs.

Real-world: e-commerce carts. Sort by price, user drags items — original order preserved for server sync. No more “why did my array shuffle?” Slack threads.

Short para. Boom.

Array.with(): The Immutable Update Hack We’ve Craved

Updating one item? Map hell for single changes. Splice? Mutates. Spread + manual swap? Boilerplate.

arr.with(2, “new value”). Magic.

Seats array, book index 2: seats.with(2, “BOOKED”). Original pristine. Negative indices too — arr.with(-1, 99) hits the last one. React cart update? setCart(prev => prev.with(index, { …prev[index], quantity: qty })). Poetry.

Performance edge: O(1) shallow copy for one change. Beats full map on 10k-item lists.

Critique time. Browser vendors dragged feet here — TC39 approved years back, but rollout lagged. Still, 2023’s Chrome dominance (68% share) means most devs live here now.

findLast: Because Reverse + Find Was Always Dumb

Last error in logs? […arr].reverse().find() — double array, mutation risk. filter.at(-1)? Unneeded full scan.

logs.findLast(log => log.status === “error”). Bam. Most recent match, forward scan stops early.

findLastIndex for the position. Chat apps: last unread message. Transaction logs: last failed payment. Version history: last autosave.

Data point: in 1M-line codebases (per GitHub stats), reverse/find patterns litter 15% of array ops. This nukes them.

URL handling was prehistoric. Manual split/decode? Encoding bombs, edge-case apocalypse.

Why URLSearchParams Crushes Your Query Parser

new URLSearchParams(window.location.search).get(“page”). Done.

Handles “?category=shoes&sort=price&page=2”. get(“missing”) returns null, no crash. has(“sort”) booleans it. Build APIs: new URLSearchParams({category: “electronics”}).toString().

No more forEach(pair => split(“=”)) fragility. Unicode? Check. Repeated keys? Arrays via getAll().

Market dynamic: Next.js, Remix — router libs lean hard here. Custom parsers? Dying breed.

Sharp position: if you’re still handwriting query logic in 2024, you’re the holdout. These APIs aren’t hype — they’re the floor for modern JS. Ignore ‘em, watch deps bloat while competitors ship lean.

Unique angle — remember Array.includes() in ES7? Killed _.includes overnight. Same trajectory: expect npm downloads for array utils to crater as CanIUse hits 99%.

FAQ time.


🧬 Related Insights

Frequently Asked Questions

What does Object.hasOwn do in JavaScript?

Replaces hasOwnProperty safely — checks own properties without overrides or prototype issues on any object.

How does Array.toSorted work?

Sorts a copy, leaves original untouched. Ideal for immutable state in React or Vue.

Is URLSearchParams better than manual parsing?

Absolutely — handles encoding, missing keys, multiples without crashes or hacks.

Priya Sundaram
Written by

Hardware and infrastructure reporter. Tracks GPU wars, chip design, and the compute economy.

Frequently asked questions

🧬 Related Insights?
- **Read more:** [Azure Logic Apps' Liquid Gamble: Shopify Magic Meets .NET Quirks](https://theaicatchup.com/article/azure-logic-apps-liquid-gamble-shopify-magic-meets-net-quirks/) - **Read more:** [Six Months After Hours: One Dev's Quest to Build Eventra and Hunt Dead Code](https://theaicatchup.com/article/i-built-eventra-in-6-months-after-my-day-job-heres-how/) Frequently Asked Questions What does Object.hasOwn do in JavaScript? Replaces hasOwnProperty safely — checks own properties without overrides or prototype issues on any object. How does Array.toSorted work? Sorts a copy, leaves original untouched. Ideal for immutable state in React or Vue. Is URLSearchParams better than manual parsing? Absolutely — handles encoding, missing keys, multiples without crashes or hacks.

Worth sharing?

Get the best AI stories of the week in your inbox — no noise, no spam.

Originally reported by dev.to

Stay in the loop

The week's most important stories from theAIcatchup, delivered once a week.