eisbehr
eisbehr

Reputation: 12452

Why to use this javascript arrow function or what is the difference?

I stumbled upon this relatively simple arrow function:

var x = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
console.log(x());

I know what it does in general. But why does it this thing so complicated? I mean, the same thing can be done much easier and has (imo) a better readability too:

var x = ([a, b] = [1, 2], c = a + b) => a + b + c;
console.log(x());

So could someone tell me the difference of this two notations or show me a better usecase for the first one?

Upvotes: 0

Views: 71

Answers (2)

nitte93
nitte93

Reputation: 1840

The 2nd argument of your 2nd is example is a simple es6 default initialization, while the 2nd argument of your 1st example is again a simple es6 default initialization with destructuring. But, I assume you already know that.

Your other part of the question was, show me a better usecase for the first one?

Destructuring is mainly useful when you want to access a key from a huge javascipt object;

Something like this:

 aHugeJavascriptObject = {
   key1:'value1',
   .
   .
   .
   key999:'value999'
 }

Now, one way to access the object's key key999 is aHugeJavascriptObject.key999, instead you probably want to do

 const { key999 } = aHugeJavascriptObject

I also assume that you already also know that. But, I am afraid that is what that is there to your question.

Upvotes: 2

nils
nils

Reputation: 27184

The first notation takes an object with a property x as the second argument. It is destructured and x is extracted as c. If it is not defined, a default object with a property x is used instead:

console.log(x([1, 2], {x: 5}));

Whereas the second one takes a simple argument primitive argument (probably a Number in this case):

console.log(x([1, 2], 5));

The only difference thus is the second argument that is fed into the function.

Upvotes: 1

Related Questions