I recently expanded on some code used as a sample in the BegJS book for determining a day so many days out from the current date. I expanded the code to ask if the user wanted to go forward or backward and how many days they wanted to go back or forward. This latter data I requested by setting up a variable, called wantedDate, and using the prompt function to get the data from the user. The problem I had, and did fix, was when going forward the code used the + operator, the code looked like this:
nowDate.setDate(currentDay + wantedDate);
The problem was
JS saw the data in the wantedDate variable as a character string and so used the + symbol to concatenate the info with a result of the currentDay and the wantedDate value joined together giving an erronious result, i.e. currentDay was 17 and wantedDate was 2, so result was 172 and this was added to the nowDate and gave the wrong result.
What I think happened was since I was using the + symbol for some reason the data in the wantedDate was seen as a character string and so
JS made the decision to concatenate. Yet the same data in the wantDated variable when used with the - operator was used as numeric data which was the intent. To get the code to see the data in the wantedDate variable as numeric data for the + operator I had to add the parseInt( ) function to convert the value to be seen as a numeric value.
nowDate.setDate(currentDay + parseInt(wantedDate);
My question is why when using the + operator was the wantedDate data seen as a character string in one area of the code and yet seen as numeric data in the other area of code, the - operator part?