If you’ve spent plenty of time wading through modern JavaScript, odds are you’ve seen enough ellipses (...) to put even the most brooding 90s role

A guide to destructuring in JavaScript

submited by
Style Pass
2024-09-27 06:00:03

If you’ve spent plenty of time wading through modern JavaScript, odds are you’ve seen enough ellipses (...) to put even the most brooding 90s role-playing game protagonist to shame. I wouldn’t fault you for finding them a little confusing. Granted, I wouldn’t fault you for finding anything about JavaScript confusing, but I’ve always thought those ellipses were uniquely unintuitive at a glance. It doesn’t help that you’ll frequently encounter these little weirdos in the context of “destructuring assignment,” which is a strange syntax in and of itself.

A destructuring assignment allows you to extract individual values from an array or object and assign them to a set of identifiers without needing to access the values of each element the old-fashioned way—one at a time, by index or key like this:

In its simplest form — called “binding pattern destructuring” — each value is unpacked from the array or object literal and assigned to a corresponding identifier, all of which are initialized with a single let or const (or var, I suppose, if you’re feeling nostalgic for function-scoping).

Leave a Comment