Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is 0 a property of trees when var trees = new Array("redwood", "bay", "cedar")

Tags:

javascript

I saw this example on mozilla documentation but i don't understand why.

if 0 is a property of trees, i was expecting that trees.0 would return redwood but is a wrong statement. Is a[0] a way to access the 0 property of the array ? In this case a["length"] should also work (logicaly). Can anyone make it clear?

link: developer.mozilla.org

var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
0 in trees;        // returns true
3 in trees;        // returns true
6 in trees;        // returns false
like image 684
Munteanu Sergiu Avatar asked Jan 15 '14 09:01

Munteanu Sergiu


2 Answers

Arrays are effectively Objects with special constraints.

In General, for an object, it doesn't matter if you write obj["key"] or obj.key. That is the reason why a["length"] works.

However - besides the fact, that a number is not a valid identifier - a.0 is not equivalent to a[0]. Since the bracket notation expects a string, an unqoted literal will be treated as name of a variable (which itself should contain a string). I'll demonstrate with a valid identifier:

obj["foo"] = "bar";
obj.foo; // -> bar

var baz = "qwert";
obj[baz] = 5;
obj.baz   // -> undefined
obj.qwert // -> 5
// or
obj["qwert"] // -> 5

An Array can also have "Object" properties (like "length"), which you can set and retrieve. So

trees.foo = "bar"
console.log(trees.foo) // -> "bar"

works. But these properties do not account to the length of the array and are also not accounted for typical methods of arrays like push and pop, etc.

like image 167
Christoph Avatar answered Sep 20 '22 00:09

Christoph


The only reason a.0 doesn't work is that a property identifier literal (the 0 part of that) isn't allowed to start with a digit. It's purely a parsing thing.

JavaScript has two ways to access properties: Dot notation with a literal, e.g. foo.bar (which has restrictions), and bracketed notation with a string, e.g. foo["bar"] (which has far fewer restrictions). (This is covered in §11.2.1 of the spec.)

JavaScript's standard arrays aren't really arrays at all in the normal sense of the term (a contiguous block of memory we index into). They're just JavaScript objects plus some special behavior. Array "indexes" are actually property names, and they're strings. (According to the specification; implementations are free to optimize this provided things behave according to the spec.)

So yes, you access the "0" property on an array using a[0] or a["0"]; a[0] being much more common and a bit easier to type. :-)

Because you can use a property using bracketed notation, a["length"] works just fine.

like image 31
T.J. Crowder Avatar answered Sep 19 '22 00:09

T.J. Crowder