Search code examples
javascriptconstructorreturnprivatepublic

JavaScript output from constructor function comes back as 'undefined'


When I pass a parameter into setGear() inside of console.log() the results come back undefined, why is this? The result should be the number I'm passing in.

var Bike = function() {
  var gear = 2;                     // private var set to an arbitrary number

  this.setGear = function(change) { // public method
    gear = change;
  };

  this.getGear = function() {       // public method
    return gear;
  };
};

var myBike = new Bike();

console.log(myBike.setGear(4)); // returns undefined, should return 4
console.log(myBike.setGear(3)); // returns undefined, should return 3
console.log(myBike.setGear(1)); // returns undefined, should return 1

Solution

  • this.setGear = function(change) { // public method
      gear = change;
    };
    

    should not return 4.

    this.setGear = function(change) { // public method
      gear = change;
      return gear;
    };
    

    should do