2

This is found in popular npm repo, http2-proxy. The code runs like this:

async function proxy (
  { req, socket, res = socket, head, proxyName },
  onReq,
  onRes
) {...}

The object with the assign operator is pass to the function. I am just wondering if this syntax is correct, since an object should use a colon(:) as an assignment operator. I tested this syntax in the console, and sure enough gives a syntax error, but since it's found in a popular repo, I assumed this is correct, but how come?

mxsxs2
  • 792
  • 3
  • 16

1 Answers1

1

Yes, this is correct syntax.

What you are seeing is known as argument destructuring, which is different from the syntax for assigning an object. The code snippet is shorthand for the following:

async function proxy (
  proxyRes,
  onReq,
  onRes
) {
  // Destructure the proxyRes object into individual variables
  const { req, socket, res = socket, head, proxyName } = proxyRes;
}

Object/argument destructuring was introduced in ES6. As ever, MDN has excellent documentation on the subject matter.

Tom Spencer
  • 6,798
  • 3
  • 48
  • 47
  • yes you're correct, it's not actually an object but a destructured parameter...and the equal sign inside the parameter refers to a default value...its kinda confusing...since it look the same...thanks! – Phaedrus Design May 13 '20 at 09:05
  • the `socket` in `res = socket` has to be defined though right? Otherwise an error will be thrown. I'm a bit confused too – Emmanuel N K May 13 '20 at 09:07
  • 1
    Nevermind. I tried it out in jsfiddle. https://jsfiddle.net/emmanuelnk/2r9usgm7/6/. I never knew you could do this. However it is important to note the order of the props in the destructure is important. Can't assign to the default value before it is defined in the object. – Emmanuel N K May 13 '20 at 09:16