DEV Community

Discussion on: JavaScript beginner help

 
roxor profile image
roxor • Edited

let day = new Date();
let birthday = day.getFullYear;
function birh(n){
let calculate = day.getFullYear - n;
return(calculate)
}

console.log(n);

Thread Thread
 
roxor profile image
roxor

something like this?

Thread Thread
 
alvaromontoro profile image
Alvaro Montoro

Those are steps in the right direction. But take into account some things:

  • You should have the variables in the scope of the function (right now you are defining the variables globally)
  • The method getFullYear() is part of Date. Considering that you are doing let day = new Date() then you'd need to do day.getFullYear() to get the current year.
  • In the console.log, you should return the result of the function and not the value that you pass to it.

With those changes, the code would look like this:

function birth(n){
  let day = new Date();
  let day1 = day.getFullYear();
  let calculate = day1 - n;
  return(calculate)
}

let n = 2000;
console.log(birth(n));

One of the things that you should do too is having descriptive names for variables. Right now you are storing dates in day, the year in day1, the birth year in n... That will be helpful in the future to maintain the code and help debug it.

Thread Thread
 
roxor profile image
roxor

Understood, in case if u want to call in another function day.getFullYear must make new, cuz this is work only in block of function birth, right?

Thank you for advice, I must try do give more descriptive names for var.

Thread Thread
 
alvaromontoro profile image
Alvaro Montoro

The variables will only work in the function/block where they were defined. So if you want to use it somewhere else, you'll need to redefine it or make it global.

Thread Thread
 
roxor profile image
roxor • Edited

I get it, thank you for the explanation you help me a lot.
When I get a job, from my first paycheck I will buy you a coffee.

thank you one more time. Cheers!