Skip to content
Advertisement

Can I destructure to multiple variables when at least one has already been declared, and at least one has not?

I’m aware that I can destructure an object or array to multiple variables, whether they are both already assigned or both unassigned, but is it possible to restructure to multiple variables together when at least one variable has already been declared, and at least one has not?

1. Both unassigned

This works ✅

JavaScript

2. Both assigned

This also works ✅

JavaScript

3. At least one assigned, and one unassigned

This DOES NOT work 🚫

JavaScript

The practical use case I am working with here is similar to this— I have a URL path that I would like to split into the path, of the same variable name and its query string when one is present.

This is what I would like to do, but it does not work for the same reason.

JavaScript

Here are a couple of workarounds I have come up with so far, but they either force me to run the function twice or break the single assignment line into three separate lines and declare a new variable simply for reassignment:

Workaround #1: Executing function twice

JavaScript

Workaround #2: Declaring temporary variable

JavaScript

Advertisement

Answer

I don’t believe there is a way to destructure into a combination of already-defined and not-yet-defined variables. But the good news is that you can simply define ahead of time all of the variables into which you wish to destructure:

JavaScript

Note that this is precisely your first attempted solution, except that we declare urlQueryString before the destructure.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement