Member-only story

JavaScript Algorithm: Convert Age to Days

(Beginner) No more mental math every time you need to translate ages

Max N
2 min readFeb 29, 2024

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) {…

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet