3

I don't have much experience with javascript and I have been looking for an explanation into this syntax so if you know it would be much appreciated if you can help me understand it!

In Node.js

const { check, validationResult }   = require('express-validator/check');
const { matchedData, sanitize }     = require('express-validator/filter');

I am used to declaring variables like this:

const name = require('npm-module..');

Could someone explain this to me?

  • it is called a destructuring assignment, you can read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment – Thijs Oct 13 '17 at 07:04
  • It's a destructuring assignment, imagine this, you have an object, that has another object with some properties that you want to get `const myObject = { coolProp: { age: 2000, name: 'super cool' } }` instead of doing it like this `const age = myObject.coolProp.age` `const name = myObject.coolProp.name` you could achieve the same with `const {age, name} = myObject.coolProp` and it would get those properties from it and give them your new variables the same name – high incompetance Oct 13 '17 at 07:13
  • wanted to provide it as an answer but these editing guys are always ruining it :) – high incompetance Oct 13 '17 at 07:14

1 Answers1

2

It is called destructuring assignment.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

You are basically telling JS that require statement will return an object, and if it can pull out for you the property

check and validationResult in 2 const with the same name.

The syntax can go deeper with assigning default values or pulling out nested objects.

AndreaBogazzi
  • 14,323
  • 3
  • 38
  • 63