Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

This question already has an answer here:

I'm having a hard time understanding this code. Could someone try to explain why an array can have elements and 0 length?

var myArray = [];
myArray["hello"] = 4;
myArray["world"] = 65;
$('#btn').on('click',function() {
    console.log(myArray.length); // Prints 0
    console.log(myArray); // Prints [hello: 4, world: 65]
    console.log(myArray.length); // Prints 0
 }
share|improve this question

marked as duplicate by Pointy javascript Jul 25 '14 at 16:11

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
this is not asynchronous, and you're using a framework hidding to you 80% of the fun of javascript. So, please don't forget it in your tags (I added it for you) – Sebas Jul 25 '14 at 16:10
    
you might want Object.keys(myArray).length, but you should likely use an object instead of an array. – dandavis Jul 25 '14 at 16:11
    
Length only adds numerically indexed properties, you're using the Array in this example as a dictionary. If you want to loop through the Array, you could put the String and Number into an Object and insert that into the Array. – Evin Ugur Jul 25 '14 at 16:14

The .length property only pertains to numerically-indexed properties.

share|improve this answer
2  
No offense, @Pointy but, although true, this isn't really the answer to the question. What he's done here is instantiate a new array object, then add properties to that object named hello and world. He's setting properties of the array object, not elements of the array itself. – Grinn Jul 25 '14 at 16:15
1  
@grinn: FWIW, array elements are so properties of the object. Every property with a numerical, positive 32bit ( or so) property name is considered to be an element . – Felix Kling Jul 25 '14 at 16:31
    
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – acrosman Jul 25 '14 at 16:59
    
@acrosman the question is a duplicate; there's a fine explanation in the linked question. – Pointy Jul 25 '14 at 17:10
    
@Grinn yes, as Felix Kling notes there really are no semantic differences between numerically-indexed properties and string-indexed properties; indeed, the numerically-indexed properties are really strings too! The .length property reflects an internal interpretation of the named properties, and those semantics are based on the properties whose names look like non-negative integers. – Pointy Jul 25 '14 at 17:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.