Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript simultaneous object and array creation

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.

like image 457
puk Avatar asked Dec 27 '22 19:12

puk


1 Answers

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.

like image 171
lonesomeday Avatar answered Dec 31 '22 15:12

lonesomeday