Why does javascript allow me to do the following.
a = {two : 'World'};
a[1] = 'Hello';
console.log(a[1]);
console.log(a.two);
the output is
Hello
World
Shouldn’t it complain that I am trying to use an object as an Array? This works with anything by the way, like so
b = new Date();
b[1] = 'Wow';
console.log(b[1]);
the output is
wow
Is there a use for this? It seems to me like a bad programing practice.
In Javascript, all arrays are objects. There is no hard-and-fast dividing line between the two. Arrays have certain properties and methods, but are implemented as objects.
The syntax
[1]is one of the two equivalent Javascript member operators. These two are equivalent:However, with the dot notation (
foo.bar), you can only access properties that are valid Javascript identifiers. This means:You can set the properties of any Javascript object — array, object, Date object, string, number — in this fashion, since they all derive from the same Object type.