1

I am new to JavaScript and learning. I see some code where variable is declared as abcBean={};

and then being used as

abcBean[SOME_SET.KEY] = false

Can someone please explain how an empty object is being used as an array?

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • `[]` sets properties by name. Array indexes are one kind of property, but they’re not the only kind of property. `abcBean.x` is equivalent to `abcBean['x']`, for example. I think this is probably a duplicate of something. – Ry- Sep 09 '15 at 18:30

1 Answers1

2

(Disclaimer: I work on Microsoft's Chakra JavaScript engine)

In JavaScript, all objects are prototype instances and their properties are defined at runtime. They can be accessed using dot-syntax (object.property) but also by name (object['property']) which enables some interesting meta-programming scenarios.

Internally (inside a JavaScript engine) JavaScript prototype objects are typically implemented as a kind of dictionary or hashtable. You can also use Number instances as keys too, not just names, which has the interesting effect of a JavaScript object exhibting a kind of duality where it is both an array (indexed by integer offset) as well as a dictionary (indexed by integer key).

For example, these four objects can be considered equivalent:

var array1 = [ 1, 2, 3 ];
var array2 = new Array( 1, 2, 3 );
var dict1 = { 0: 1, 1: 2, 2: 3 };

function Constructor() { this[0] = 1; this[1] = 2; this[2] = 3; }
var dict2 = new Constructor();

In practice, engines have optimizations where JavaScript arrays and objects are handled differently based on their initialization syntax. Internally in Chakra the array1 and array2 objects will be represented as an array of integers but dict1 and dict2 will both be hashtable objects, however if you add a non-integer element to array1 or array2, or add an element by key, then Chakra will (behind the scenes) re-represent the object internally as a hashtable (or some other more appropriate representation).

Of note, this will not internally expand array1 to an 101-element-sized array:

var array1 = [ 1, 2, 3 ];
array[100] = 5;
Dai
  • 141,631
  • 28
  • 261
  • 374