Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named array element used in function definition

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?

like image 543
iPath ツ Avatar asked Oct 03 '16 21:10

iPath ツ


2 Answers

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()); 
like image 64
Rob M. Avatar answered Sep 21 '22 12:09

Rob M.


This seems to be destructuring as @Xufox correctly pointed out.

Function parameters can in fact have destructuring:

  1. go to https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
  2. Search for this text: Pulling fields from objects passed as function parameter
  3. 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.

like image 39
Sumit Maingi Avatar answered Sep 21 '22 12:09

Sumit Maingi