4

On this page (https://nodejs.org/api/modules.html), I found this writing: { }.

const { PI } = Math;

Does it have a particular name, so that I can get more information about it, and especially what does it produce?

Thanks in advance. :D

  • 1
    it is called [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), where a property of an object is now a variable with the same name. – Nina Scholz Sep 18 '18 at 20:49
  • In this case, it is the same as writing: "var myObject = { x : 1 }; var x = myObject.x;" no ? I must have missed something... –  Sep 18 '18 at 20:56
  • that a longer form. but you could use more properties at the same moment for destructuring. – Nina Scholz Sep 18 '18 at 20:58
  • All right, I see, all his interest lies in the destructuring of several properties. Thank you! –  Sep 18 '18 at 21:04

2 Answers2

6

This is called "destructuring assignment". You can think of it as being equivalent to:

const PI = Math.PI;

…but a little more compact. It really shines when being used to pluck multiple properties off an object:

const { foo, bar, baz } = require('quux').util;

You can also destructure arrays using [ ]:

const [ first, second, third ] = array;
Ben Blank
  • 54,908
  • 28
  • 127
  • 156
1

The curly brackets in javascript typically represent an object, but in this case, it is a "destructuring assignment". For example:

const obj = { value: 'hello world' };
const {value} = obj;
console.log(value); // outputs: hello world
Ken Bigler
  • 587
  • 1
  • 4
  • 15