thegunmaster
thegunmaster

Reputation: 295

object in javascript function definition

My friend was just making some nonesense code, or atleast I thought he was, but to my surprise it did not throw any error. It however did not do what he expected, as he didn't really know what he was doing. But now I am quite curious what it does do, because there must be some reason it doesn't throw an error. The code looked something like this:

var n = function(someArg, anotherArg, {help: []}){};

Also, when adding data into the object, it throws an error:

var n = function(someArg, anotherArg, {help: ["something"]}){};

Throws: 'Uncaught SyntaxError: Unexpected string'

so why is a random argument allowed?

Upvotes: 1

Views: 76

Answers (1)

Barmar
Barmar

Reputation: 782693

This is EcmaScript 6 argument destructuring. If you define a function as:

function myfun({help: [a, b, c]}) {}

You can then call it as:

myFun({help: [1, 2, 3]});

and it will bind the arguments a, b, and c to 1, 2, and 3 respectively. Your example is simply a degenerate case of this, where the array containing the variables is empty.

In a destructuring argument list, the places where expressions can go in an ordinary object or array literal have to contain a variable name, as that's the variable that will be bound to the corresponding element in the argument object/array. This is why the second version produced an error: "something" is not a variable name, it's a string, so it can't be used in a pattern.

Upvotes: 3

Related Questions