10

So I have:

// some function that returns two arrays ..
getArrays() {
  return {
    arr1: [...],
    arr2: [...]
  };
}

// and then ..
let arr1 = [];
let arr2 = [];
if (someCondition) {
  { arr1, arr2 } = getArrays();
}

// here we expect arrays, even if they are empty ..

Of course, this throws an error. Is this even possible?

PS: I can use default values and directly call the function, but still - I think it should be possible.

pesho hristov
  • 1,946
  • 1
  • 25
  • 43

1 Answers1

18

One solution is to wrap the destructuring expression with parentheses:

// some function that returns two arrays ..
function getArrays() {
  return {
    arr1: [1],
    arr2: [2]
  };
}
const someCondition = true;
let arr1 = [];
let arr2 = [];

if (someCondition) {
  ({ arr1, arr2 } = getArrays());
}

console.log(arr1, arr2);

Another solution is to move the condition to the getArrays() function, and if the condition is false return two empty arrays:

const getArrays = (condition) =>
  condition ? 
    { arr1: [1], arr2: [2] }
    :
    { arr1: [], arr2: [] };

const someCondition = true;
const { arr1, arr2 } = getArrays(someCondition);

console.log(arr1, arr2);

You can also use the condition and ternary outside of the function:

const getArrays = () => ({ arr1: [1], arr2: [2] });

const someCondition = true;
const { arr1, arr2 } = someCondition ? getArrays() : { arr1: [], arr2: [] };

console.log(arr1, arr2);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • The first solution is perfectly what I wanted :) ... as I don't want to bloat the function with more code, and furthermore - the condition is not one and the same on the different places I'm using this. Thank you:) – pesho hristov Nov 02 '18 at 12:37
  • Your welcome :) I've added another to use the condition outside the function. – Ori Drori Nov 02 '18 at 12:42
  • Hello, just to understand this methodology, what's the use case for doing it this way? getArrays() returns an object with 2 arrays. You could easily just declare an object let's say 'let arrays' then use the function 'arrays = getArrays();' and then use it like 'console.log(arrays.arrr1)' and 'console.log(arrays.arrr1)'. Since is the first time i see your approach, can you explain on which scenarios this will be useful? – Ph0b0x Nov 02 '18 at 12:48
  • This is called destructuring. You use it when you want to assign parts of an array/object to one variable or more. You should read more about [Destructuring assignment on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment). – Ori Drori Nov 02 '18 at 17:28