2

When reading through the documentation for an NPM package, I came across the following code:

const {OperationHelper} = require('apac');

This object was then used later like so:

const opHelper = new OperationHelper({..})

I'm unfamiliar with the {OperationHelper} assignment - a variable name inside a pair of braces. I actually didn't even think this was valid syntax. What is this called and how does it work?

Taneem Tee
  • 517
  • 3
  • 8
  • 1
    Here is the MDN definition. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring – Vito Aug 06 '17 at 02:17

1 Answers1

1

  const testObject = {
    name: "myName",
    lastname: "lastName",
    address: "myAddress"
  }

  const {name, address} = testObject

  alert(name)
  alert(address)

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

Which means in the assignment you are telling give me the value of the property OperationHelper from the module require('apac') and store it in a variable named OperationHelper. Check this small sample I have created

Pato Salazar
  • 1,447
  • 12
  • 21