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.
In this case, the correct syntax is to put the destructuring expression inside parenthesis ( (...) ). Please note that the parenthesis are required when you want to omit the let or const keyword in the destructuring expression itself.
Destructuring nested objectsIf we need to access an employee's info we can destructure as many levels as it takes to get to our employee object's properties. const { engineers: { 1: { id, name, occupation, }, }, } = employees; Now we have access to all of the second employee object's properties.
Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that's more convenient. Destructuring also works great with complex functions that have a lot of parameters, default values, and so on.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With