1

I'm trying to learn javascript (coming from Delphi/pascal) and am unclear about the similarities and differences between object properties and array values. I did try searching the archives and the web for this answer.

Consider the following code:

function Show(Arr) {
  var str ='';
  for (var Val in Arr) {
      str += Val + '::' + Arr[Val] + '\n';
  }   
  return str;
}
var str = '';
var A1 = ["Yellow", "Red", "Blue"];
var A2 = {"color":"red", "Size": 5, "taste":"sour"}

alert(Show(A1));
//OUTPUTS: 
//    0::Yellow
//    1::Red
//    2::Blue

A1.push("Green");
alert(Show(A1));
//OUTPUTS: 
//    0::Yellow
//    1::Red
//    2::Blue
//    3::Green

alert('Length: '+A1.length);
//OUTPUTS: 
//   Length: 4

alert(Show(A2));
//OUTPUTS:
//  color::red
//  Size::5
//  taste:sour

alert('Length: '+A2.length);
//OUTPUTS: 
//   Length: undefined

A2.push("Green");
//ERROR --> execution stops on jsfiddle.net. 
alert("OK");  //<-- never executed
alert(Show(A2));  //<-- never executed

I know that almost everything is an object in javascript. I have been reading here (http://javascript.info/tutorial/objects) and here (http://www.w3schools.com/js/js_objects.asp).

I see that an array can be accessed by index, e.g. A1[3] --> Blue, as in other languages. But I see also that a property can be accessed this way, e.g. A2["Size"] --> 5. So at first blush, it looks like array values and property values are essentially the same. But arrays can be extended with a .push(value) command, whereas properties can't.

It is coincidence that my Show function works for both arrays and objects?

Actually, as I have written this and researched the topic, is it just that all arrays are objects, but not all objects are array? So then does the for...in loop in Show() actually work differently depending on which type of object is sent in?

Any help clarifying this would be appreciated. Thanks.

kdtop
  • 541
  • 1
  • 7
  • 22
  • 2
    Uh… http://w3fools.com – bjb568 Apr 05 '14 at 00:29
  • Maybe this post will also give you some insight http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea – icanc Apr 05 '14 at 00:29
  • @bjb568 -- But their site is to pretty! I saw reference to this site the other day, but read it today. I hear them when they say that there are inaccuracies, but when I click on the alternatives, they seemed target for advanced users, and they seem harder to get info from. Thanks for the heads up. – kdtop Apr 05 '14 at 00:46
  • @icanc -- That was a helpful link. Thanks! – kdtop Apr 05 '14 at 00:58
  • @kdtop Is [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/JavaScript_Overview) really that hard to understand? – bjb568 Apr 05 '14 at 01:42
  • @bjb568. That is a good site. Thanks for the link. – kdtop Apr 05 '14 at 16:24

1 Answers1

2

So at first blush, it looks like array values and property values are essentially the same.

Array entries and object properties are indeed the same thing, because JavaScript's standard arrays aren't really arrays at all, they're just objects with some added features. Two of those features are the special length property, and the push function, which is why you don't see those with A2.

Your observation about bracketed notation is particularly spot-on. In JavaScript, you can access object properties using bracketed notation and a string, like this:

var o = {answer: 42};
console.log(o['answer']); // 42

It's not well-known that this is exactly what you're doing when using an array "index":

var a = ['a', 'b', 'c'];
console.log(a[1]); // b

The 1 we're using with a[1], technically according to the specification, is coerced to a string (a["1"]), and then that property name is used to look up the property on the object.

So then does the for...in loop in Show() actually work differently depending on which type of object is sent in?

No, for-in works the same with all objects. It iterates the names of the enumerable properties of the object. Whether you're using an array or any other object doesn't matter.

Note that not all properties are enumerable. For instance, Array#length isn't, nor is Array#push or Object#toString or any of the other built-in properties of objects.

But for instance, you can see that for-in is the same for arrays as for other objects like this:

var a = ['zero'];      // An array with one entry
a.answer = 42;         // We've added a property to the object that isn't an array entry
console.log(a.length); // 1, because `length` only relates to array "indexes" as
                       // defined by the specification
var key;
for (key in a) {
    console.log(key + "=" + value);
}
// Shows (in *no reliable order*):
// 0=zero
// answer=42

More about for-in:

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875