-3

I'm trying to understand what this declaration means

const { headers, method, url } = request;

I tried to check if request here is an object, so I tried to output it to console but received errors. I also tried to print "headers", "method" or "url", separately, and even as request.headers, request.method, and request.url but that also produced errors.

Eddie
  • 25,279
  • 6
  • 26
  • 53
ronan marsh
  • 75
  • 1
  • 10

3 Answers3

4

Destructuring Assignment in ES6

Destructuring can be a harder concept to grasp, because there’s some magic going on… let’s say you have simple assignments where keys house and mouse are variables house and mouse:

var data = $('body').data(), // data has properties house and mouse
  house = data.house,
  mouse = data.mouse

ES5 :

var jsonMiddleware = require('body-parser').json

var body = req.body, // body has username and password
  username = body.username,
  password = body.password 

ES6 :

var {house, mouse} = $('body').data() // we'll get house and mouse variables

var {json: jsonMiddleware} = require('body-parser')

var {username, password} = req.body

Source

Jeremy M.
  • 1,043
  • 1
  • 6
  • 25
  • `var {json: jsonMiddleware} = require('body-parser')` is really a lot harder to read than the equivalent ES5, though – Bergi Feb 27 '18 at 10:04
2

This is an destructuring assignment. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

It let you avoid code like this:

const headers = request.headers;
const method = request.method;
const url = request.url;
Mark Labenski
  • 321
  • 3
  • 10
2

This is called object de-structuring.

You are effectively unpacking whatever is in request and creating three const assignments, one for headers, method and url.

The value of say headers will be equal to the value of request.headers.

dougajmcdonald
  • 17,178
  • 7
  • 49
  • 87