0

Are these constructions the same?

const {PI} = Math;

and

const PI = Math.PI;

What are benefits of using the first example?

3
  • 1
    The first is just a shorthand syntax for the second (ES6). See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    – haim770
    Mar 12, 2018 at 9:43
  • 1
    it lóòks more cool ... Mar 12, 2018 at 9: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.) Mar 12, 2018 at 9:51

2 Answers 2

1

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

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

-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

4
  • 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. Mar 12, 2018 at 9:48
  • @T.J.Crowder take it easy and let people get some reputation :D Mar 12, 2018 at 9: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) Mar 12, 2018 at 9: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, 2018 at 10:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.