Changing a variable with closure

Tell us what’s happening:
How do you change the variable hatchedEgg in the below example? I understand the idea that you need to make a private variable so it can’t be changed on accident, but what if you want to be able to change it?

  **Your code so far**

function Bird() {
let hatchedEgg = 10;

this.getHatchedEggCount = function() { 
  return hatchedEgg;
};
}
let ducky = new Bird();
ducky.getHatchedEggCount();

Challenge: Use Closure to Protect Properties Within an Object from Being Modified Externally

Link to the challenge:

You set and get the data from inside the function scope using functions/methods you control. The user of the API can still interact with the data just not without using your API (i.e. the methods you have in place for interacting with the data).

The point is no direct access to the data is allowed from the outside.

So to change hatchedEgg, I just go into the function and change the numbers manually?

What if more eggs are hatched and a user wants to input that information? I don’t understand.

No, you create a method that can be called on the instance which allows the user to change it. The internal logic controls how they can, or can’t change it.

function Bird() {
  let hatchedEgg = 10;

  this.getHatchedEggCount = function () {
    return hatchedEgg;
  };

  this.setHatchedEggCount = function (count) {
    if(count < 1) return;
    hatchedEgg = count;
  };
}

let ducky = new Bird();
console.log(ducky.getHatchedEggCount()); // 10

ducky.setHatchedEggCount(5);
console.log(ducky.getHatchedEggCount()); // 5

ducky.setHatchedEggCount(0);
console.log(ducky.getHatchedEggCount()); // 5

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.