Age calculator challenge

Define a function called ageCalculator. This function should take three parameters:

  • name: a string representing someone’s name
  • yearOfBirth: a number representing their year of birth
  • currentYear: a number representing the current year

The ageCalculator function should return a string stating how old the person is. For example, if you called ageCalculator("Suzie", 1983, 2015);, the return value should be as follows:

"Suzie is 32 years old.";

My code:

const ageCalculator = {
  name: "James",
  yearOfBirth: 1992,
  currentYear: 2024
};

const age = ageCalculator.currentYear - ageCalculator.yearOfBirth;

console.log(ageCalculator.name + " is " + age + " years old.");

TypeError: ageCalculator is not a function.

It won’t run, I need help.

Your ageCalculator is indeed an object and not a function.

What would be the correct code?

you need to have ageCalculator be a function, for starter

We cannot write the correct code for you.

As the others have mentioned, you need to have a function, not an object like you did here

Here is a good article going through functions in javascript

But the main reason why this lesson wants you to use a function instead of an object is for the resuability aspect of it.

Looking at your current code, you have an object where the properties only work for one person.
James

But what if we wanted to calculate the age for
Suzie or
Jessica or
Jeremy or
Ilenia or
Nick, etc

By using a reusable function, then you can call that function multiple times with different pieces of data

hope that helps

I found the correct one.
Thank you guys for the help! :grinning:

function ageCalculator(name, yearOfBirth, currentYear) {
  const age = currentYear - yearOfBirth;

  console.log(name + " is " + age + " years old.");
}

ageCalculator("James", 1992, 2024);

Maybe instead for searching for a solution, you should try to write it. You learn more writing code yourself, than finding it.

1 Like

I misread the problem, I was doing an Object instead of a function. I got the answer correct after trying to solve it. Thanks to these guys!