Cautis Marius
Cautis Marius

Reputation: 21

Javascript age calculator not working, it returns a string

I need a bit of help with this code. It returns a string instead of the required result and I'm a bit stuck.

function calculateAge(name, birthYear) {
    this.name = name;
    this.birthYear = birthYear;
    this.result =  function(){
        var currentYear = new Date().getFullYear();
        return currentYear - birthYear;
    };
    document.write("Hi there " + this.name + " ." + "You are " + this.result + " old !" ); 
};

var John = new calculateAge("ion" , 1980);
John.result();

Upvotes: 1

Views: 43

Answers (1)

kind user
kind user

Reputation: 41893

Call the function to get the desired result - this.result().

function calculateAge(name, birthYear) {

  this.name = name;
  this.birthYear = birthYear;
  this.result = function() {
    var currentYear = new Date().getFullYear();
    return currentYear - birthYear;
  };
  document.write("Hi there " + this.name + " ." + "You are " + this.result() + " old !");
};
var John = new calculateAge("ion", 1980);
John.result();

Upvotes: 1

Related Questions