2

I followed the instructions in this question.

Here's my code:

    edate = new Date()
    edate.setYear(edate.getFullYear() + 1);
    month = edate.getMonth();
    console.log(month);
    console.log(month.length);

This returns:

3
undefined
H. Soares
  • 203
  • 5
  • 22
MorganFreeFarm
  • 3,811
  • 8
  • 23
  • 46
  • 1
    Be careful re setYear: "[This feature is no longer recommended](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setYear). Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it" – Andy Apr 16 '19 at 14:56
  • `setFullYear`: read the link in the comment. – Andy Apr 16 '19 at 14:59

1 Answers1

3

In the code you listed from the other question, the value stored in month was converted to a String. This can be done like this (concatenation with empty String causes toString() conversion):

month = '' + edate.getMonth();

A Number value does not have a length property, but a String does. This is what the original code was utilizing.

Update

A more clear approach (as mentioned) would be to utilize the String constructor that accepts a Number as input and converts it to a String, like so:

month = String(edate.getMonth());

Or, you could call toString() directly on you the value that is returned from getMonth(), like so:

month = edate.getMonth().toString();
Tim Klein
  • 2,538
  • 15
  • 19
  • 1
    add this to your answer `String(edate.getMonth())`. It can also be use to coerce a number into a string – 0.sh Apr 16 '19 at 15:00