FAQ: Advanced Objects - Getters


#1

This community-built FAQ covers the “Getters” exercise from the lesson “Advanced Objects”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript

FAQs on the exercise Getters

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!


#3

Please could someone explain why the end of this lesson the answer is:

console.log(robot.energyLevel)

and not

console.log(robot.energyLevel())

and when to know when to put the brackets in please?


#4

Hi, I am just learning about getters and setters myself and without seeing your code I can’t be sure,
but I believe that when calling getter and setter methods, the function is called without ().


#5

This makes sense actually I think they did mention that somewhere and I forgot! Thank you for your help


#6
get attribute () {
    return this._attribute;
}

We write a get call the way we would access an object property, normally.

console.log(object.attribute);

We know there is no literal attribute by that name, but a backing variable with an underscore, which value is returned by the getter. We never invoke the getter method as we would a typical method, since it is self-invoking and accesses the actual attribute and returns it.

Likewise, we never invoke a setter, but call it like we would be making an assignment.

object.attribute = newValue;

The mechanics behind the scene are such that we cannot access (get) a variable while it is being set. It’s a bit complicated to fully understand, let alone explain, but warrants further study as you get more immersed in the finer details. Add this to your reading list.