0

Hi everyone, I'm in the process of learning Javascript and I'm confused about having a function inside another function, in particular the argument part.

I've included a sample code from the lesson where it's looking to calculate the years until retirement for three people given their year of birth.

What I'm confused about is the year within the function yearUntilRetirement(name, year).

Shouldn't this be yearOfBirth instead of year since it's looking back at the calculateAge(yearOfBirth) function to find the age? Or is this argument only unique to the function it is currently in?

function calculateAge(yearOfBirth) {
    var age = 2016 - yearOfBirth;
    return age;
}

function yearsUntilRetirement(name, year) {
    var age = calculateAge(year);
    var retirement = 65 - age;
    console.log(name + ' retires in ' + retirement + ' years.');
}

yearsUntilRetirement('John', 1990);
yearsUntilRetirement('Mike', 1969);
yearsUntilRetirement('Mary', 1948);
3
  • argument names dont matter as long as the type is same; for example if year is a string, u will have issues; you can replace year is anything else and still ur code will work fine; Commented Dec 4, 2017 at 8:47
  • 1
    This is more about consistency. From a language point of view, the name of the variable is determined by the position: the first argument passed year is within the scope of the calculateAge interpreted as yearOfBirth. Naming variables consitently improves understanding. Commented Dec 4, 2017 at 8:48
  • You should have a look at scopes (w3schools.com/js/js_scope.asp) Commented Dec 4, 2017 at 8:50

1 Answer 1

1

Maybe this will clarify.

When you call yearsUntilRetirement(name, year), you pass in two values as the arguments. Such as yearsUntilRetirement("John", 1975). Then, inside of the function yearsUntilRetirement, the other function calculateAge is called, using the value of year as the argument. Since year is the value 1975, we get age = calculateAge(1975). Now, within the calculateAge function, the value 1975 is the value corresponding to yearOfBirth. So, running everything through, you get var age = 2016 - 1975.

If this is too drawn out, I will attempt to clarify further. Drop a comment if you need anything else.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much for the explanation and thank you to everyone who helped me in this literally within minutes after I posted! I only have a vote to give, otherwise I'd give it to all that's helped!
No problem. Happy coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.