-1

im a c programmer and im starting with JS. I have a date and i want to make a function that: -Recieves a month and a year and checks if the date is invalid, and corrects it (month will never be bigger than 24).

const check_month = (month, year) => {
  if(month > 12){
   month = month - 12;
   year = year + 1;
  }
}

The problem is that when i exit the fuction, month and year variables are not actually modified outside that function, so i understand that im passing it copies of my variables, not the actual reference of the variable. I thought about giving it a return but i cant return multiple values at once (i would have to return year and month), so im a little bit lost. Maybe returning

date = {month, year};

return date;

?

Could you help me? Thank you

3
  • 1
    Why is this surprising to you? You said you're a C programmer, and the same thing would happen in C. Parameters are passed by value, and assigning the local variable doesn't affect the caller's variable. Commented Sep 1, 2022 at 20:35
  • In c I use pointers to solve this Commented Sep 2, 2022 at 2:27
  • JS doesn't have pointers, although you can use containers (objects or arrays) for similar purposes. Commented Sep 2, 2022 at 2:44

2 Answers 2

1

If you return the object, you can use destructuring.

const check_month = (month, year) => {
  while(month > 12){
   month = month - 12;
   year = year + 1;
  }
  return {month, year}
};

{month, year} = check_month(month, year);

I also changed if to while so that this will work for months above 24 as well.

Sign up to request clarification or add additional context in comments.

Comments

0

Or you can pass an object as the argument. Objects are always passed by reference:

const adjust_month = o => {
  o.year+=Math.floor(o.month/12)
  o.month=o.month%12;
  return o;
};
const monthYear={month:25,year:2020};
adjust_month(monthYear);
console.log(monthYear);

console.log(adjust_month({month:63,year:2017}));

I added the return o; into the function, so the modified object o can be assigned to another variable or be used directly in an expression.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.