I'm learning JavaScript after C, and the amount of new syntax is a bit overwhelming. Do people use array and object destructuring often, or is it fine to stick with separate assignments? Does it get easier to read with practice?
How often is destructuring used in JavaScript?
Answers
Yes, you'll encounter destructuring often enough that it's worth learning to read, even if you don't use it much in your own code yet. It's an alternative to separate assignments, not something JavaScript requires.
In a shared codebase, local conventions may make the choice for you. Otherwise, use whichever version makes the code easier to follow.
Reply to this answer
Start with the simplest cases. For an object, const { job, city } = person takes the properties named job and city and puts their values in variables with those names. For an array, const [first, second] = values takes values by position instead.
The rest syntax in your example is an extra piece. In const { job, city, ...remainingProperties } = person, the last variable gets a new object containing the remaining enumerable own properties. You don't need to memorize every variation at once.
plainlyspoken:
That new object is a shallow copy, so any nested objects in it are still shared references.
Reply to this answer
Readability depends on who's reading and what the code is doing. A couple of named properties can be easier to scan when destructured, but a complicated pattern can be harder to follow than separate assignments. It's fine to look up syntax when you forget it.
Reply to this answer
Some tools and codebases use it a lot. React code, for example, often destructures props, so recognizing the pattern is useful even if you prefer explicit assignments elsewhere.
Reply to this answer
Feeling buried in syntax is normal when a language is new. Don't try to cram every form. Practice with small bits of code, use the forms you understand, and check a reference when something unfamiliar comes up.
Reply to this answer
Add your answer
Answers are reviewed before publication.
post-lunch-hypothesis:
That helps. Reading it first sounds less daunting than trying to use every variation right away.