Imagine this scenario where I keep my field name in a variable like this -
const NAME_FIELD = 'name';
Then, I go ahead and use this inside an object like this -
let state = {
[NAME_FIELD]: 'ashwani'
}
console.log(state) // Output - { name: "ashwani" }
All good till now. Now, later in my code, I want to get value of this same key. Ofcourse the easy way out is to simply use something like state[NAME_FIELD]
. I am using destructuring though.
With destructuring, this works -
const { [NAME_FIELD]: x } = state;
console.log(x) // Output - ashwani
But, my first attempt to this was like this -
const { name } = state; // This works as expected
const { [NAME_FIELD] } = state; // I was expecting this to work too, but it didn't
I expected the above code const { [NAME_FIELD] } = state;
to work but it didn't while the other ones worked. Will be really great if someone can help me understand that :)
I know that JS throws a parse error when I say const { [NAME_FIELD] } = state;
. With my question, I am trying to understand why ECMAScript team would have made this decision and what is it I am missing in my understanding. In the later comments, some of SO members have provided certain useful views on this.