Is this Javascript syntax correct { req, socket, res = socket, head, proxyName }?

Viewed 43

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?

1 Answers

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.

Related