Console.log misleadingly says array.length = 0

Hi,

please have a quick look at this CodePen:

When I console.log() the length of the array, it returns 0 … even though I can iterate through the array. Why is that?

Kind regards
Thomas

Hey,

This looks a bit like PHP to me:

var array = new Array;

array['a'] = 'a';
array['b'] = 'b';
array['c'] = 'c';

console.log(array.length);

for (var key in array) {
  console.log(key);
}

PHP does not distinguish between indexed and associative arrays, whereas JavaScript does (in so far as JS only has indexed arrays*, for an associative array you would use an object).

var array = [];

array[0] = 'a';
array[1] = 'b';
array[2] = 'c';

console.log(array.length);
=> 3

Perhaps you are trying to do this:

var obj = {
  "a": "1",
  "b": "2",
  "c": "3"
}

console.log(obj.a);
=> 1

This might help: How to Create and Manipulate Arrays in JavaScript

* Kinda: http://stackoverflow.com/questions/1076658/javascript-array-associative-and-indexed

What you’re doing in your pen is adding additional properties to your array object, not array-elements. This doesn’t increment its length, and you can’t access these properties with native array methods – e.g. try array.pop(), which will return undefined. If you want to get the “length” of your object, try

console.log(Object.keys(array).length);

instead. Iterating over the (enumerable) properties works for any object however, which is why you’re getting the output you’re expecting in the for ... in loop.

1 Like

Wow, thanks so much! :thumbsup:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.