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.
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.
Share Improve this question asked Nov 2, 2018 at 12:15 pesho hristovpesho hristov 2,0602 gold badges27 silver badges50 bronze badges 1- Just add parens – Jared Smith Commented Nov 2, 2018 at 12:17
1 Answer
Reset to default 19One 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);