-1

Could anybody explain why the output of the code

var a = [1,2];
console.log("Array item: " + a[a=a.toString(), 1]);
console.log("String char: " + a[1]);

looks like this?

Array item: 2                                                                   
String char: , 

The question is why array didn't convert to string in the first console.log. How do memory and pointers work in this case?

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
Tetyana
  • 83
  • 1
  • 10

2 Answers2

3

a[a = a.toString(), 1] evaluates a at first, which points to an array yet, then it replaces a with a stringified a which won't affect the already evaluated part, then accesses index 1 of the array. Its the same as:

var b = a;
a.toString();
b[1]

Now a[1] evaluates to , because a points to the string now, and therefore it gets the second character.

Here is how the parser sees it:

a[a = a.toString(), 1]
// Evaluation of a
[1, 2][a = a.toString(), 1]
// Evaluation of the comma operator, a is turned into a string
[1, 2][1]
// Prop access
2
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

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.
          +--------+-----------------+
Ele
  • 33,468
  • 7
  • 37
  • 75