Page 1 of 2
results in the string value "51" being stored in j i.e. 2+3 is 5 and then "5" is concatenated with "1". On the other hand
stores the string "123" in j.
This is perfectly reasonable as the expression is evaluated left-to-right and i+2 results in a string and so (i+2)+3 is another string.
results in the numeric value 6 being stored in j.
Again perfectly reasonable as the unary + can only be interpreted as a numeric operator so the string has to be converted to a number to make it work and from this point on everything is a number.
2+3+i is the same as (2+3)+i which is number+string i.e. string
i+2+3 is the same as (i+2)+3 which is string+number i.e. string
+i+2+3 is the same as ((+i)+2)+3) which is number+number i.e. number
Even though all of these are perfectly reasonable it is enough of a possible confusion to prefer explicit type conversion where ever it is obvious that it is needed.
With this advice ringing in our ears the next example should seem very reasonable. It is very simple but you have to remember that it is the essence of something that happened within a lot of code doing lot of other jobs. This however is the essence of what was going on.
The programmer obtained a date string from the user split into day, month and year. The problem was that the day number had to be converted and used as an integer index later in the program.
For the sake of simplicity in the example the day variable is just set to an appropriate string. The parseInt function is then used to convert it to an integer before the arithmetic, also simplified, is performed:
The division just serves to make the point that daynum is supposed to be numeric.
This code works - or sometimes works.
After some testing with multiple browsers it was noticed that occasionally the program crashed because 100/daynum returned infinity.
Investigations revealed that it only happened on two particular dates and not in all browsers.
What are the dates and why does it happen?
Turn to the next page when you are ready to find out.