0

Are these constructions the same?

const {PI} = Math;

and

const PI = Math.PI;

What are benefits of using the first example?

Dmytro Plekhotkin
  • 1,877
  • 2
  • 21
  • 47
  • 1
    The first is just a shorthand syntax for the second (ES6). See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring – haim770 Mar 12 '18 at 09:43
  • 1
    it lóòks more cool ... – Nina Scholz Mar 12 '18 at 09:44
  • *"Are these constructions the same?"* They have the same result: A constant called `PI` with the value from `Math.PI`. *"What are benefits of using the first example?"* You avoid having to repeat the identifier `PI`. In the general case, if you are picking more than one thing (`const {a, b, c} = obj;`), you avoid repeating `obj.` *and* the identifier names. In general, avoiding repetition is good because it removes an opportunity for error (e.g., changing one of them and not the other, mistyping one, etc.) – T.J. Crowder Mar 12 '18 at 09:51

2 Answers2

1

The curly braces around the variable name is called Destructuring assignment,

and const {PI} = Math; will translate to const PI = Math.PI

programtreasures
  • 4,104
  • 1
  • 7
  • 25
-1

It is a so-called "destructuring assignment".

Searching this site I found a similar question with a good answer: Javascript (ES6) const with curly braces

ar34z
  • 2,422
  • 2
  • 21
  • 35
  • 1
    *"Searching this site I found a similar question with a good answer:"* Then comment saying you've found a duplicate (and when you have enough rep, close vote), don't post an *answer*. – T.J. Crowder Mar 12 '18 at 09:48
  • @T.J.Crowder take it easy and let people get some reputation :D – Amani Ben Azzouz Mar 12 '18 at 09:53
  • 1
    @AmaniBenAzzouz: I am taking it easy. SO will turn into a morass of useless duplication, like every attempt at solving this problem before it, if people constantly post duplicate answers. *(Not my dv, btw, ar34z)* – T.J. Crowder Mar 12 '18 at 09:57
  • Oops, you're right @T.J. Crowder. My bad. It's been a while since my last activity here... All the answers here have been downvoted without any comment (as you haven't done mine). That doesn't help any of them at all either. I'll vote for this one though. – ar34z Mar 12 '18 at 10:06