Member-only story
Dealing with age values in code often requires translating between units — years, months, days, etc. Rather than googling conversions on the fly, let’s set up our own reusable function to handle the math once and for all!
In just a few steps, we’ll take a number representing age in years and return the total days that equals. Let’s begin.
Defining Our Year-to-Day Function
First, we set up the function signature with the years parameter:
function yearsToDays(years) {
}
By adding years here, we indicate any value passed during function calls should go into that variable.
Calculating Total Days
Inside the function body, we simply multiply the years by 365:
function yearsToDays(years) {
var days = years * 365;
}
Easy math! Since there are 365 days per year, this formula does the conversion perfectly.
Returning the Result
Finally, we return the total days back out of the function:
function yearsToDays(years) {…