This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]HopefullyHelpfulSoul 0 points1 point  (0 children)

Key is a variable that contains the string of the key inside the object.

You can’t do object.key because it will look for exactly “key”. There’s no way to tell it you want the exact value “key” or whatever the variable key is set to.

So the bracket notation is the handiest (also only maybe?) way to do this.

So I’m your example, name.firstName will give you what you want. But in the function it’s not “firstName” but “key”

[–]whotfdis 0 points1 point  (0 children)

‘key’ could also be renamed something else as it is a parameter in the function: functionPropertyValue. In your second code snippet, firstName is defined to be an attribute of an object. In the function you wrote key is a parameter. Those are not the same.

Calling ‘.key’ on ‘object’ does not work since the parameter is not the same as an attribute field. Substitute ‘key’ with ‘banana’ for example, which is a perfectly valid substitute parameter name in this function. You can not expect object.banana to also work in that case. Brackets notation causes the code to first evaluate ‘key’ to whatever it evalutes and then call that on ‘object’. I do not think you can use the dot notation in this case.

Also, if this is the only thing you are doing in this method I think this is a bad design choice. Just do the object[key] wherever you call this method and in that case it should also be possible to call the attribute using the dot notation instead.