4

It's not clear what this syntax means

const { headers, method, url } = request;

found in this tut https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/

user310291
  • 36,946
  • 82
  • 271
  • 487

4 Answers4

7

It's called destructuring operator.

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

Simple example:

var obj={
   "a":2,
   "b":3
}
let {a,b}=obj;
console.log(a,b);

From your example, I saw that request is an object and the statement is translated to

headers = request.headers

But you can also apply destructuring operator for arrays.

var foo = [1, 2, 3];
var [one, two, three] = foo;
console.log(one);
console.log(two);
console.log(three);
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
2
const headers = request[0];
const method = request[1];
const url = request[2];

if request is an object,

const headers = request.headers;
const method = request.method;
const url = request.url;
Avinash
  • 779
  • 7
  • 18
1

If request is an object, it means:

const headers = request.headers;
const method = request.method;
const url = request.url;
lone_worrior
  • 232
  • 2
  • 15
1

It’s called destructuring. Check it out at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment Ie. you can get nested properties inside of an object. In your case it is res

It can be more convenient to access props from an object by destructing props to a local variable instead of writing the whole namespace like request.headers

Staplerz
  • 85
  • 1
  • 10