Recently I 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 variable that references item with index 0 in the first argument (declared as array).
My questions are:
1) How is this syntax named (the [param1] part that lets you use param1 as variable)?
2) Why does "Case 2" work? Is there any automatic conversion?
As @Xufox pointed out, this works because of destructuring
(array destructuring, to be more specific). Your second example works because a string is an array-like object, so you get T
, which is param1[0]
. Numbers are not arrays (or even array-like), so the the engine fails to destructure the argument.
If you coerce your number to a string it will work:
foo((123).toString());
This seems to be destructuring as @Xufox correctly pointed out.
Function parameters can in fact have destructuring:
Now the above shows an example of another kind of destructuring, example given below:
function userId({id}) {
return id;
}
var user = {
id: 42,
displayName: "jdoe"
};
console.log("userId: " + userId(user)); // "userId: 42"
however, I assume it applies to this as well:
function foo([param1]) {
console.log(param1);
}
Difference between integers and strings in this behaviour:
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 strings are nothing but an array of chars, its perfectly fine that it works actually.
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