0

This:

x = ({ title, description }) => { console.log(title, description) }

Works like this: (at least in terms of accessing the variables)

x = (title, description) => { console.log(title, description) }

It was quite surprising to me. First the first method describes the passed parameter as an object with certain keys title and description, but what is even more surprising, one can then access the values as normal variables.

Is it some syntactic sugar? Where is it mentioned in specification? This new JS is quite confusing.

luky
  • 1,787
  • 1
  • 17
  • 26
  • 1
    It's called [destructuring assignment](https://www.ecma-international.org/ecma-262/6.0/#sec-destructuring-assignment). – undefined Sep 08 '18 at 17:31
  • 1
    1st one pass object with de-structuring object literal Like below:x({title:'A',description:'B'})=>A B. 2nd one is normal parameter passing. – prajitgandhi Sep 08 '18 at 17:31
  • 1
    [Here is an example from MDN on how deconstructing can be used to benifit](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Setting_a_function_parameter's_default_value) – vityavv Sep 08 '18 at 17:33
  • 1
    its a syntactic sugar in my opinion. When we have variable with same name as object properties,we use this.Say let a='A',b='B', we can write x= {a:a,b:b} as an object or x ={a,b} which is equiv to x= {a:a,b:b} – prajitgandhi Sep 08 '18 at 17:35
  • but you realize that in the body you dont acces the first parameter as an object but you access solo variables. so it must be some special syntactic sugar rule. but with all these unexpected rules the new JS becomes quite not understable – luky Sep 08 '18 at 17:35
  • i know but this is not even destructuring, it is declaring an object that has keys title and description.. so its even more another rule + some special rule of accessing the keys just like normal variables. but console says it is destructuring though (if you dont pass any param) – luky Sep 08 '18 at 17:41
  • 1
    hm so yes it is really deconstructing and that's the explaining of it.. interpreter takes the definition of the arguments like {title, description} and does the assingment of passed argument like {title, description} = {title:"", description:""} that's why it works as title and description in the body. but pitty this wasn't mentioned anywhere but ok. – luky Sep 08 '18 at 17:48

1 Answers1

1

That is ES6's Destructuring assignment

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Mamun
  • 58,653
  • 9
  • 33
  • 46
  • ok but here you dont use assignemnt. here you declare the arrow function so its not assingment in my opinion. so it must be some other special rule – luky Sep 08 '18 at 17:32
  • Object destructuring syntax, yes, but not an assignment. – Bergi Sep 08 '18 at 19:08