Search code examples
javascriptarrow-functions

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?


Solution

  • 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.