Can anyone explain how the why/how the below method of assigning keys in JavaScript works?
a = "b"
c = {[a]: "d"}
return:
Object {b: "d"}
The [] operator converts the expression inside the square brackets to a string. For instance, if it is a numeric value, JavaScript converts it to a string and then uses that string as the property name, similar to the square bracket notation of objects to access their properties.
An object can be created with figure brackets {…} with an optional list of properties. A property is a “key: value” pair, where a key is a string (also called a “property name”), and value can be anything. Let us visualize this with the following syntax for creating an object in JavaScript.
Bracket notation is another way to access a property of an object. To use bracket notation, write the name of the object, followed by brackets [] . Inside the brackets, write the property name as a string. Bracket notation, unlike dot notation, can be used with variables.
An object contains properties, or key-value pairs. The desk object above has four properties. Each property has a name, which is also called a key, and a corresponding value. For instance, the key height has the value "4 feet" . Together, the key and value make up a single property.
It's the new ES2015 (the EcmaScript spec formally known as ES6) computed property name syntax. It's a shorthand for the someObject[someKey]
assignment that you know from ES3/5:
var a = "b"
var c = {[a]: "d"}
is syntactic sugar for:
var a = "b"
var c = {}
c[a] = "d"
Really the use of []
gives an excellent way to use actual value of variable as key/
property while creating JavaScript objects.
I'm pretty much statisfied with the above answer and I appreciate it as it allowed me to write this with a little example.
I've executed the code line by line on Node REPL (Node shell).
> var key = "fullName"; // Assignment
undefined
>
> var obj = {key: "Rishikesh Agrawani"} // Here key's value will not be used
undefined
> obj // Inappropriate, which we don't want
{ key: 'Rishikesh Agrawani' }
>
> // Let's fix
undefined
> var obj2 = {[key]: "Rishikesh Agrawani"}
undefined
> obj2
{ fullName: 'Rishikesh Agrawani' }
>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With