1

I am running Node v6.6.0, which has support for destructuring function arguments:

function foo ({ a: { b }}) {
  // stuff
}

Suppose I want to destructure and access both a and b. Sadly the following doesn't seem to work:

function foo ({ a: { b }}) {
  return [a, b]
}
foo({ a: { b: 123 }})
// ReferenceError: a is not defined!

Is this bug in Node or is this the expected behavior for ES6? Shouldn't both a and b be defined in the function? If not, why does destructuring have the effect of un-defining a base property name (a)?

Is there a way I can use parameter destructuring to get both a and b defined in the function? I'm explicitly trying to avoid manually destructuring them.

1
  • a merely designates what property of the parameter b is to be taken from. It is not defined or accessible as a parameter. If you want to access a, you will have to extract b yourself within the function. Commented Aug 1, 2017 at 16:05

1 Answer 1

4

Is this bug in Node or is this the expected behavior for ES6?

This is expected behaviour. Because {a: {b}} doesn't bind a as a name it just indicates you want to access a property of the destructured object.

You could use the following.

function foo ({ a, a: {b} }) {
  return [a, b]
}
console.log(foo({ a: { b: 123 }}))

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, so simple! That didn't even cross my mind as a possibility. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.