Named array element used in function definition

I recently discovered that this syntax works in JavaScript (Chrome 53):

function foo([param1]) { // Function argument is declared as array and param1 is used as variable? What is the name of this syntax? console.log(param1); } foo(['TestParameter1']); // Case 1 - works. Output: TestParameter1 foo('TestParameter1'); // Case 2 - works??? Why? Output: TestParameter1 foo(123); // Case 3 - does not work - VM860:1 Uncaught TypeError: undefined is not a function(…) Result => TestParameter1 // this is the result 

I see that param1 can be used as a variable that refers to an element with index 0 in the first argument (declared as an array).

My questions:

1) What is this syntax called (the [param1] part, which allows you to use param1 as a variable)?

2) Why does Case 2 work? Is there an automatic conversion?

+6
source share
3 answers

As @Xufox pointed out, this works because of destructuring ( destructuring the array to be more specific). The second example works because the string is an object like an array , so you get T , which is equal to param1[0] . Numbers are not arrays (or even like arrays), so the engine cannot destroy the argument.

If you force your number to a string, it will work:

 foo((123).toString()); 
+3
source

This is similar to restructuring, as @Xufox correctly pointed out.

Functional parameters can actually have a restructuring:

however, I believe this applies to this:

 function foo([param1]) { console.log(param1); } 

The difference between integers and strings in this behavior:

 console.log('123'); //works, outputs 1, '123' = ['1', '2', '3'] of chars console.log(['123']); //works, outputs 123 console.log([123]); //works, outputs 123 console.log(123); //error 

In the above example, since the strings are nothing more than an array of characters, it can be clearly seen that it actually works.

+2
source

These brilliant people above say the same thing. Here's how the computer reads this:

foo ('testParamater1') = foo (['testParamater1']);

but...

foo (123) = foo ([[1,2,3]);

Unfortunately, for your particular use case, not the same. Excuse me!

0
source

All Articles