 # I just learned how to use Math.abs() in a problem

I just learned how to use Math.abs() in a problem
0

#1

I recently got back into CodeWars, and worked on a problem were I had to create a generator that lets the user find out how old will he/she be within future years and vice versa (i.e. how many years till you’re born).

I just learned to use Math.abs( ) in a problem where I had to use the absolute value in a way so that I can display a different sentence if the age or years till birth was 1.

by = Birth Year
cy = Chosen Year

``````function calculateAge(by, cy) {

var diff = Math.abs(by - cy);

if (by < cy && diff === 1) {
return("You are 1 year old.");

} else if (by > cy && diff === 1) {
return("You will be born in 1 year.");

} else if (by < cy) {
// You are x years old
var age =  cy - by;
return("You are " + age + " years old.");

} else if (by > cy) {
// You will be born in x years
var yearsBirth = by - cy;
return("You will be born in " + yearsBirth + " years.");

} else {
return("You were born this very year!");
}
}``````