I recently came across some code which I am a little confused about. Below is similar code, have a look:
var x = [];
console.log(x); // prints [] (no surprise)
x[0] = "abc";
console.log(x); // prints ["abc"] (no surprise)
x["test"] = "testing"
console.log(x); // prints ["abc"]
console.log(x.test); // prints "testing"
so in this case.. the same variable, x
, is both array and an object. How is this possible? If it acts as both, then console.log(x)
should print something like ["abc",test:"testing"]
but that syntax is wrong.
So whats happening in this case?