简体   繁体   中英

Newbie Trying to Build a Javascript Age Calculator

I'm a new self-learner and have recently taken on javascript. I have an assignment (from an online code camp) that I just cant seem to make pass. I feel like I understand the basics of it, but I can't write it in a functional way. Can anyone help me here?

年龄计算器

The question is in the attached image.

My code looks a little something like:

function ageCalculator(name, yearOfBirth, currentYear) {
  var age = currentYear - yearOfBirth;
  return (name + "is" + age + "years old.");
  console.log(ageCalculator("Miranda", 1983, 2015));
}

I would appreciate any help! Thank you!

You're calling the function ageCalculator just after the return statement. Anything just after the return statement won't be called.

Just pull that call outside.

 function ageCalculator(name, yearOfBirth, currentYear) { var age = currentYear - yearOfBirth; return (name + " is " + age + " years old."); } console.log(ageCalculator("Miranda", 1983, 2015)); 

Call the function outside the function declaration.

 function ageCalculator(name, yearOfBirth, currentYear) { var age = currentYear - yearOfBirth; return (name + " is " + age + " years old."); } console.log(ageCalculator("Miranda", 1983, 2015)); 

Whenever you return , the function stops immediately: it'll never get to your console.log the way it is now. Call console.log and the function itself outside your function, you don't want an infinite recursive loop.

Also make sure to add proper spacing:

 function ageCalculator(name, yearOfBirth, currentYear) { var age = currentYear - yearOfBirth; return (name + " is " + age + " years old."); } console.log(ageCalculator("Miranda", 1983, 2015)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM