I simply can't wrap my head around "computed properties", I have googled around but it didn't help much, the website I am following says this, but could anyone make it clearer? I know it's spelled out to me but I still couldn't really understand what it's trying to tell me. Could you try to say it in "simple words"?
We can use square brackets in an object literal. That’s called computed properties.
For instance:
let fruit = prompt("Which fruit to buy?", "apple"); let bag = { [fruit]: 5, // the name of the property is taken from the variable fruit }; alert( bag.apple ); // 5 if fruit="apple"
The meaning of a computed property is simple:
[fruit]
means that the property name should be taken fromfruit
.So, if a visitor enters
"apple"
, thebag
will become{apple: 5}
.
The part I can't understand is the
alert( bag.apple ); // 5 if fruit="apple"
{ fruit: 5 }
, then the key would befruit
, no matter whether a variable namedfruit
existed or not - because that is a text literal at this point. So if you want to specify the key dynamically, you either need to use this syntax, orbag[fruit] = 5
(in that case thebag
would need to exist prior to that line.) – CBroe Nov 1 '17 at 10:43let fruit = "apple"
without the prompt, but they wanted to explicitly make the variable value dynamic. – Bergi Nov 1 '17 at 10:44