Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array destructuring in function parameters

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?

like image 640
leonardofed Avatar asked Jul 13 '18 13:07

leonardofed


People also ask

What is parameter Destructuring?

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.

Can we Destructure function in JavaScript?

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.

Can you Destructure an array?

You can destructure an array more than once in the same code snippet.


1 Answers

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.

like image 74
trincot Avatar answered Oct 04 '22 04:10

trincot