Novice in javaScript

Hello seniors,

In the script below , kindly explain what is the role of “parameter x” in age method and what value is it being assigned and from where ?

It’s totally going over my head.
Many thanks.


class Car {
  constructor(name, year) { = name;
    this.year = year;
  age(x) {
    return x - this.year;

const date = new Date();
let year = date.getFullYear();

const myCar = new Car("Ford", 2014);
"My car is " + myCar.age(year) + " years old.";

Hi @Azhar1,

Edit: I edited your post for readability. Whenever you post code to the forum, please highlight and click the </> button in the tools above the editor where the bold, italics, and such are.

x in this instance just refers to the passed in year that is being compared to the car’s model year. A better parameter name for x might be passedInYear so that it reads as:

age(passedInYear) {
 return passedInYear - this.year;

But if you can’t change it, that’s understandable.

What it does is returns the current age of the vehicle. So, in your example, you pass in 2014 as the model year for the vehicle to start. You then pass in the current year by getting that from today’s date which becomes 2023 - 2014 making it 9 years old.

Does that means x spontaneously get assigned the year value from the date method?

what I am not getting is just how x here connects to the year value from the date, because whatever I replace x with I am getting the same result.

Thanks for tip above .

So, x in this case is just the parameter name. If you pass in a different value, keeping the same Class, you’ll get a different result like so:

const myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML= "My car is " + myCar.age(2020) + " years old.";

If you run that part, that’ll give you a car that is 6 years old because I’m passing in 2020 in that innerHTML command.

It matters what value you pass into it, not necessarily what it is named. I brought up the name so that you might better understand what role x plays in this situation.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.