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 β
let [a, b] = [1, 2];
2. Both assigned
This also works β
let a, b; [a, b] = [1, 2];
3. At least one assigned, and one unassigned
This DOES NOT work π«
let a; [a, b] = [1, 2]; // ππΌ let [a, b] = [1, 2]; // ππΌ
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.
let urlPath = '/some-path/some-page?parameter=value'; const getUrlParts = url => url.split('?'); [urlPath, urlQueryString] = getUrlParts(urlPath); // ππΌ
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
let urlPath = '/some-path/some-page?parameter=value'; const getUrlParts = url => url.split('?'); const urlQueryString = getUrlParts(urlPath)[1]; urlPath = getUrlParts(urlPath)[0];
Workaround #2: Declaring temporary variable
let urlPath = '/some-path/some-page?parameter=value'; const getUrlParts = url => url.split('?'); const urlSplitData = getUrlParts(urlPath); // temporary variable created property = urlSplitData[0]; const urlQueryString = urlSplitData[1]; // temporary variable no longer needed
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:
let urlPath = '/some-path/some-page?parameter=value'; let urlQueryString = ''; const getUrlParts = url => url.split('?'); [urlPath, urlQueryString] = getUrlParts(urlPath);
Note that this is precisely your first attempted solution, except that we declare urlQueryString
before the destructure.