Markese P Markese P - 7 months ago 17
Javascript Question

Please help me with my method

Hello I am new to JavaScript and I can't figure out my problem.
When I enter my code like this it works, if the

birth year + age === 2016
or if it's not
=== 2016
it logs both statements correctly

var newAge = function (yearsAlive) {
yearsAlive = this.yearBorn + this.age ;
if (yearsAlive === 2016) {
document.write("That Sounds about right to me ! ");
} else {
document.write("Your age cant be right , please try again");
}
} ;
var me = {
name: "Markese" ,
yearBorn: 1991,
age: 25,
years: newAge
} ;
me.years()


But when I try to enter my code, like this, with user input using prompt it doesn't work. I keep getting the
else
log:
Your age cant be right, please try again
even if it is
=== 2016
. What am I doing wrong?

var userName = prompt("Whats your name?") ;
var userBorn = prompt ("Hey " + userName + " What year where you born?") ;
var userAge = prompt ("hmm so if you were born " + userBorn + " that would make
you how old today?") ;
var newAge = function (yearsAlive) {
yearsAlive = this.yearBorn + this.age ;
if (yearsAlive === 2016) {
document.write("That Sounds about right to me ! ");
} else {
document.write("Your age cant be right , please try again");
}
} ;
var me = {
name: userName ,
yearBorn: userBorn,
age: userAge,
years: newAge
} ;
me.years() ;

RJM RJM
Answer

I don't know what your prompt function looks like, but I'll assume it's returning a string that the user types in. In your working code, me.yearBorn and me.age both contain numeric values. But in your non-working code, you're assigning a string to those. So when you later add the two strings together, it's not doing an arithmetic add operation. It's concatenating the two strings. So the result will never equal 2016. You need to convert the strings into numbers using parseInt(). Try this...

var me = {
    name: userName , 
    yearBorn: parseInt(userBorn), 
    age: parseInt(userAge),
    years: newAge
};