howOld() code review

Hello lovely codeacademy people, I am once again asking for advice on how I could clean up this code, as it fulfills the requirements of the JavaScript challenge, howOld(), but feels incredibly messy.

const howOld = (age, yearInput) => {
  let currentYear = 2021;
  calcAge = yearInput - currentYear + age;
  if (yearInput > currentYear){
    return `You will be ${calcAge} in the year ${yearInput}.`
  } 
  let birthYear = (currentYear - age);
  if (yearInput < birthYear){
    newYear = birthYear - yearInput;
    return `The year ${yearInput} was ${newYear} years before you were born`
  } if (yearInput > birthYear && yearInput < currentYear) {
    return `You were ${calcAge} in the year ${yearInput}.`
  }
}

Honestly I’m just glad to have fulfilled the logic but it seems like a pretty shoddy way of doing it, so anything would help really!

Hey Callum! :slight_smile: How are you doing?

What is it the you think is messy in your code?

For me it seems like there are too many variables announced within the block of the function, so maybe it is more of a mathematical problem that I could use different operators to get to the same conclusion?

I hope that makes sense, thank you!

The thing I noted immediately is this conditional:

  } if (yearInput > birthYear && yearInput < currentYear) {
    return `You were ${calcAge} in the year ${yearInput}.`
  }

I would have used an else if instead.

About the number of variables, it depends, I think that when you’re writing down what is in your mind, it’s good to keep things clear and tidy, using comments about what you want to write in a particular block and what result you’re expecting from it, and so on, then once the program works you can refactor it to make it more concise.

If you want to eliminate your variables you can drop calcAge, birthYear and newYear and put their formulas directly inside the curly brackets of the placeholder $.

If you look at the structure of your conditionals you see that you could actually nested them:

if (a<b){ //do something }else{ if(a<c){ //do something else }else{ //definitely do this instead } }

nesting is usually considered less human-readable, but is also more efficient.

I am also a big fan of ternary conditionals and I often use them more than I should. If you want to test yourself try to refactor your code using a nested ternary. :slight_smile:

1 Like