How to manage the soft fail of the nested arrays in ES6?
Let's say we have a nested array with items and we want to get the first item:
const array = [[3,4,5,6]];
const [[firstItem]] = array; // firstItem = 3
console.log(firstItem);
I would like to protect against the situation when the array comes with a null
, but apparently it doesn't work similarly to handling object soft fail:
const array = [null];
const [[firstItem] = []] = array; // Uncaught TypeError: array is not iterable
console.log(firstItem);
From destructuring assignment:
Default values
A variable can be assigned a default, in the case that the value unpacked from the array is
undefined
.
You have null
as value and not undefined
.
const array = [undefined];
const [[firstItem] = []] = array; // Uncaught TypeError: array is not iterable
console.log(firstItem);