Make Object Properties Private - what's wrong with this code?

I have passed the excercise mentioned in the title, but I spent hours trying to figure out what was wrong with my last code, until i made a small change and passed it. And I don’t want to leave without knowing what was the problem with my last code.

Here’s the code that could not pass:

var Bike = function() {
  var gear = 0;
  this.setGear = function(val) {
    gear += val; 
  this.getGear = function() {
    return gear;

var myCar = new Car();

var myBike = new Bike();


To make it work, I changed the first few lines in the constructor function to:

var gear;
  this.setGear = function(val) {
    gear = val; 

So why does the latter code work and not the first one? I feel like they should be doing the exact same thing.

Because setter functions are used to set the value not to increase it.

1 Like
  1. gear += val; --> notice += is increment

  2. gear = val; --? notice= is assignment,

I assume first code was incrementing value by argument and thats why you didnt pass the test,
in the variable “gear” there was wrong value.