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/
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/
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);
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;
If request is an object, it means:
const headers = request.headers;
const method = request.method;
const url = request.url;
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