0

Is it possible to both destructure a variable and have access to the structured variable in the same call?

For example, what could I replace ??? below to get the desired output (and how else might I have to edit my code)

const foo = ({ a, b }) => {
  console.log(a) // 1
  console.log(b) // 2
  console.log(???) // { a: 1, b: 2 }
}
const x = { a: 1, b: 2 }
foo(x)

My goal is knowledge and succinct code - I want to avoid const { a, b } = params as the first line of foo() in the case where I might need to pass the entire params object on.

Toni Leigh
  • 4,830
  • 3
  • 22
  • 36

1 Answers1

0

If the first argument is an object whose reference you want, it's not possible - once you destructure an argument, there's no longer any way to reference to the full argument, only some of its properties.

It would be possible if the object and parts you wanted was part of a larger object, though, because then you can reference the property name alone (to get the object into a variable), and then reference it again to destructure, eg:

const foo = ({ obj: { a, b }, obj }) => {
  console.log(a) // 1
  console.log(b) // 2
  console.log(obj) // { a: 1, b: 2 }
}
const obj = { a: 1, b: 2 }
foo({ obj })

Your original code could work to an extent if the object had a property that referenced itself, but that's pretty weird:

const foo = ({ a, b, obj }) => {
  console.log(a) // 1
  console.log(b) // 2
  console.log(obj) // { a: 1, b: 2 }
}
const x = { a: 1, b: 2 }
x.obj = x;
foo(x)
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Then I'd replace the commonly expected `vals = { a, b } = params` with the somewhat unexpected `x.obj = x;` ! – Toni Leigh Oct 11 '19 at 07:40