I have something here related to array destructuring that I don't fully understand.
In the following example:
function foo( [a, b, c] ) {
console.log(a, b, c)
}
foo( 1, 2, 3 );
When I run this I get the following error:
Uncaught TypeError: undefined is not a function
Now, I am not questioning the fact that this doesn't output 1, 2, 3
as one might expect since only the first value 1
actually get destructured (a = 1[0], b = 1[1], c = 1[2]
).
But here's the thing:
I can perfectly write 1[0], 1[1], 1[2]
and I get undefined
for each of those.
Then why the foo
function I wrote above throws an exception instead of simply returning 3 times undefined
as I'd expect.
Indeed, if I write bar
as following, I am getting 3 undefined
as should happen.
function bar() {
console.log( 1[0], 1[1], 1[2] )
}
bar();
// undefined undefined undefined
Can someone tell me what JS does in the first foo()
and why the output it's not undefined undefined undefined
?
Destructuring in JavaScript is used to unpack or segregate values from arrays or properties from object literals into distinct variables, thus it allows us to access only the values required.
JavaScript Object Destructuring is the syntax for extracting values from an object property and assigning them to a variable. The destructuring is also possible for JavaScript Arrays.
You can destructure an array more than once in the same code snippet.
Destructuring with an array pattern uses iteration in the background, i.e. the value being destructured must be iterable.
In fact, in Firefox, the error message seems more indicative:
TypeError: (destructured parameter) is not iterable
That is where the comparison you make with evaluating 1[0], 1[1], 1[2]
goes wrong: that does not need 1
to be iterable.
A more correct comparison would be to do this:
console.log([...1]);
// or:
const [a, b, c] = 1;
...and that code will fail.
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