Skip to content Skip to sidebar Skip to footer

Understanding Computed Properties (square Brackets)

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 k

Solution 1:

You're saving the value of the prompt in a variable called fruit. In this case, it defaults to "apple".

You're then declaring another variable, bag. bag has one property, which here is [fruit]. This will evaluate to the value of fruit at runtime, effectively making the declaration

let bag = {
  'apple': 5
};

The alert function will then alert the value of bag.apple. bag.apple has a value because you set bag[fruit] to be 5 when you declared the bag variable, and fruit is 'apple'.

Solution 2:

javascript is different in this as in Python d={xx:11} d set to be { xx: 11 } Now

key="we"d={[key]:22}

d1 set to be { we: 22 } Python would not accept xx - it would be not-defined. But js will see xx as a string 'xx'. If you want to use it the Python way, you have to use [key]:22 as in above.

Solution 3:

The visitor doesn't have to enter "apple". It was supplied as the default in the prompt. Only by modifying the alert: alert(bag[fruit]) could the user enter a different value in the prompt, e.g., "banana" and get the alert to report 5 instead of undefined. I use computed values mostly for returning an iterator from an iterable function:

let interator = iterable[Symbol.iterator]();

, and object keys that have spaces or characters that don't conform to the production for a JavaScript identifier.

Post a Comment for "Understanding Computed Properties (square Brackets)"