What you're facing is evaluation order, access order and how the memory is storing the values.
Javascript as other languages evaluates from right to left, Although the comma operator evaluates first a=a.toString()
in memory a
equals to [1,2]
because the most at right value will be evaluated first before modifying the variable a
, so a[1] = 2
.
After that access, the variable a
equals to "1,2"
and a[1] = ,
, in memory a String is like an array of chars and is possible to access using indexes.
This is how the access occurs:
+------------+-------------+
| Var a | Access |
+------------+-------------+
+--| [1,2] | a[1] -> 2 |-+---> This is the first access.
Memory | +--------+-----------------+ |<--- Here the first value no longer exists and now a = String.
+--| "1,2" | a[1] -> "," |-+---> This is the second access.
+--------+-----------------+