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 βœ…

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.

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