How is this code correct "tempObj['num']"?

https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/learn-javascript-objects/quizzes/learn-javascript-objects-objects-quiz

In this quiz, I struggled to understand this question, but finally cannot.

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

I think that tempObj[‘num’] searches ‘num’ key. So, doesn’t tempObj[‘num’] return error ?
I researched how tempObj[’_num’] works, then this code returns 22.

Could someone teach me how tempObj[‘num’] work ?

 > tempObj.num()
 X Uncaught TypeError: tempObj.num is not a function

Behind the scenes the getter is called as if we wrote, tempObj.num.

Thank you so much, I’m glad to hear that the getter is called when we write tempObj[‘num’] as if wrote tempObj.num.

1 Like

I just did this quiz as well: tempObj[‘num’] will search for the num key, and will find the getter num. Since getters are a special case, you call them without the (), like you would for a regular method defined as a function

So writing tempObj[‘num’] is the same as writing tempObj.num which will call the getter and print 22. tempObj.num() will give a syntax error. tempObj._num will return 22 omitting the getter function all together.

1 Like

The role of the getter is to obscure the backing variable which we don’t want exposed. The only place that variable should be visible is in the getter or the potential setter.

Just to make sure I understand the meaning of your comment: are you saying tempObj._num does not bypass the getter? Or are you saying such syntax shouldn’t be used?

From what I learned (and I am exactly a week into JS, so total noob), nothing in JS prevents accessing object properties directly, even if getters are defined. Is that not right?

That’s the suggestion, yes.

Correct. They are not private, as it were, just obscured.

1 Like

Great, thank you for the clarification! I guess codeacademy should work on the distractors in the original quiz question haha

1 Like