Question about the output of a get method

This is the link to the question.
this is the code

let tempObj = {    
_num: 22,    
get num() {        
return this._num;    }};

my question:
why does console.log(temObj['num'];
outputs 22??
‘num’ is a string not a variable with a value.
Thank you

You are right that num is a string, all JS object keys are strings, even though we don’t need quotes on the literal. However, being as it is a key, we are polling the associated value, 22.

Above the code is accessing the getter property which accesses the backing variable and its value, 22, which is then returned to the caller.

We can, full knowing it exists, access the getter with standard dot notation…

console.log(temObj.num)

Note that there are no quotes like there are in the subscript.

Thank you for your reply.
Very helpful.
the issue is that the string num is not the string _num
so how could the string num access the value stored in the key with the string _num?

The getter property polls the backing variable (this_num) and returns the value it gets back.

return this._num

When we access the getter property, tempObj.num, it invokes the method which has the above return. That is why,

tempObj.num

gives, 22.

so is this correct:
console.log(tempObj['num']) === console.log(tempObj.num)

It remains confusing to me that a string notation ‘num’(which looks like an element in an array, is treated as the get function.
Maybe I just need to accept that these are the rules. This is how it is… :slight_smile:

‘looks like’, but is not. It is a subscript of the object, and denotes value that is associated with the key.

object[key]

where key is a variable.

object['name']

where name is a physical key name, akin to,

object.name

Thank you for your reply.
I have done more study of object and getters and setters.
I now see where I went wrong.
I also still think that something abouth the syntax does not feel intuitive. But that is obviously just a subjective perspective.
so in conclusion:
tempObj['num'] is the same as tempObj.num
and I would use the bracket notation in case a key is more than one string(word)
Thank you for your replies

1 Like