FAQ: Advanced Objects - Privacy

This community-built FAQ covers the “Privacy” 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 Privacy

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!

_ before the name of a property to mean that the property should not be altered

const robot = {
  _energyLevel: 100,
  privacyLevel: 100
};
console.log(robot._energyLevel = 'high'); //high
console.log(robot.privacyLevel = 'zero'); //zero

but I change keys in robot obj, with underscore or without, so what’s the point of that ? _

like it says, should not, unfortunately JS does not enforce encapsulation like Java

1 Like

so what’s the point of it? o-O

Its a convention, letting developers know getters and/or setter should be used to modify the property.

1 Like

got it, so In big projects, where a lot of people work, that “_” means that we shouldn’t change the value, even tho we can?

yes, for example:

obj = {
    _a: [],
    get a(){
      return this._a;
    },
    set a(value){
      if (this._a.includes(value)){
        console.warn(`${value} already in array`);
        return;
      }
      this._a.push(value);
    }
}

obj.a = 3;
obj.a = 4;
obj.a = 5;
obj.a = 3;
console.log(obj.a);

lets say for whatever reason we need an array which can only contain unique values, we can bypass the setter, but then we also bypass the validation (which is done in the setter) which can cause issues further down in the code

Just did some Googling to see if we could create hidden properties for objects. I wanted to see if I could hide the property in a way so that even if you look at the length of the object it would not be counted. Also if you happened to find the property it can not be changed.

Here I have defined my robot object. Notice that the _enegeryLevel property has been removed.

const robot = {
  recharge(){
    this._energyLevel += 30;
    console.log(`Recharged! Energy is currently at ${this._energyLevel}%.`)
  }
};

Here I am able to use the keys() method to check how many properties my object has.

let keyCount = Object.keys(robot);
console.log(keyCount.length);
// Output = 1

Then I use defineProperty method with my object. It creates the property _energyLevel and sets it some rules.

Object.defineProperty(robot, "_energyLevel", {
    enumerable : false,
    value : 100,
    writable: false
});

Attempting to change the property.

robot._energyLevel = 200;

Property remains unchained.

console.log(robot._energyLevel);
// Output = 100
1 Like

why not just go back up into the existing code and change it to ‘high’?

Object.freeze() will prevent properties from being altered, right? Though I don’t know if this lesson wants us to prevent elements from being altered. Instead, I think they want us to safely change the value of a property (if the value of a property couldn’t be 3, we could use setters to assign whatever value the developer wants, except if it was 3)

In this topic about privacy, it is mentioned that an underscore must be added before the property name as a naming convention so that others can understand that the property must not be mutated. However, if an underscore is added, shouldn’t the property name be declared as a string. In the earlier chapters, I learnt that any special characters used in keys must be declared as a string. Am I missing something?

1 Like

JavaScript has a few rules regarding naming variables:

Naming Variables: Rules and Best Practices | Understanding Variables in JavaScript | InformIT

the same rules apply to properties of an object. An underscore is actually allowed.

1 Like

Thank you so much! I get it now! :smile:

A post was split to a new topic: Advanced objects - privacy

Can anybody please illuminate me? Have I done something weird in this exercise, because they said that a ‘funky string’ is printed to the console, but I was expecting it to look like this ‘high30%’ and why is there an undefined in my code? Can anybody please tell me what is the ‘type-coercion’ thing is supposed to make me see? My code below:

const robot = {
_energyLevel: 100,
// this recharge() method adds 30 to the energy level
recharge(){
this._energyLevel += 30;
console.log(Recharged! Energy is currently at ${this._energyLevel}%.)
}
};
// this line reassigns the ‘_energyLevel’ property from the robot object to ‘high’
robot._energyLevel = ‘high’;

// this line prints the text contained within the recharge() method and modified using the reassignments above
console.log(robot.recharge());

the recharge method does not return, yet when you call the method you attempt to log the returned value:

console.log(robot.recharge());

What is a good use case for private variables and what would be the consequence of not making them private?

Why doesn’t robot[_energyLevel] = ‘high’; work to reassign the value of the _energyLevel property?

I thought that you could use brackets to access any property. I also understood that dot notation cannot be used with properties that have special characters. Why isn’t an underscore _ considered a special character?

1 Like

how about #? :sweat_smile: more actually now, no? :thinking: