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:
var foo = {};
foo.bar = 'foobar';
foo['bar'] = 'foobar';
However, with the dot notation (foo.bar
), you can only access properties that are valid Javascript identifiers. This means:
a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number (source)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With