javascriptoperator-precedenceassociativity

Why does an addition like string + number + number concatenate the numbers as strings?


ok, I'm writing a little code snippet to get the ISO date-format value for yesterday.

code:

var dateString = new Date();

var yesterday = dateString.getFullYear();

    yesterday += "-"+dateString.getMonth()+1;

    yesterday += "-"+dateString.getDate()-1;

The above code outputs 2009-111-23. It is clearly not treating dateString.getMonth() as an intiger and tacking 1 on to the end of it.

Does putting the "-"+ in front of dateString.getDate() cast getDate() into a string?

this works gets the desired result.

var dateString = new Date();

var yesterday = dateString.getFullYear() + "-";

    yesterday += dateString.getMonth()+1+ "-";

    yesterday += dateString.getDate()-1;
//yesterday = 2009-12-22

Although I don't really like the way it looks... whatever no big deal.

Can anyone explain to me why javascript acts like this? is there any explanation for why this happens?


Solution

  • This is about associativity. + operator is left-associative, so

    "-"+dateString.getMonth() + 1
    

    is same as

    ("-"+dateString.getMonth()) + 1
    

    Put parenthesis around the expression you want to be evaluated first:

    "-" + (dateString.getMonth() + 1)