Carter Li
Carter Li

Reputation: 159

What is "function f(a = {} = {} = {}) {}"

enter image description here

It won't throw syntax error. What does it mean?

Upvotes: 1

Views: 164

Answers (2)

Nick Parsons
Nick Parsons

Reputation: 50864

It's a function which is using a default parameter and destructuring assignment.

The first thing to note is that:

{x} = {x:1, y:2}

will evaluate to {x:1, y:2} while setting x to be 1.

With that in mind your function does your operations in the following order, where each {} to the left of the = is destructuring syntax:

f(a = ({} = ({} = {})))

Above, we perform the most inner {} = {} first. This syntax is destructuring the empty {} object, so no variables are initialized, all it does is evaluate to an empty object {}. Now that that's evaluated, you can perform {} = {} again for the next set of parenthesis. This again just evaluates to {}.

Now that this is evaluated you evaluatively set a = {}, which sets the default parameter for a.

You can see this in action a little better by assigning the right-most object some properties and then destructuring those:

function f(a = {z} = {x, y} = {x: 1, y: 2, z:3}) {
  console.log(a, x, y, z);
}
f();

Upvotes: 4

Andrew Arthur
Andrew Arthur

Reputation: 1603

The default value of a is an empty object.

f();

function f(a = {} = {} = {}) 
{
    console.log(a);
}

Output:

Object {}

Upvotes: 0

Related Questions