re: How to Get an Object Length VIEW POST


Semantics: A JS object is a collection of properties, keys that map to their respective values, with keys that can only be strings or symbols. It doesn't have a length.

Similar to asking "What is the length of your car?" and giving the answer "The length of my car is 14, because it has 4 doors, a trunk, 6 windows, and 4 wheels".

(Simplified example.)

Using Object.keys().length or Object.getOwnPropertyNames().length gives the length of the list of enumerable keys (or all property names for the latter), not of an object.

Not judging though. I just enjoy being explicit/intentional with wording when I can. Good article and thanks for sharing. :)

Something you could add: Using an object as a key calls .toString(), which will make all object keys conflict on the key "[object Object]". ES6' Map works with objects but uses their memory address as keys, so an exact copy of an object will have a different key (no deep comparison, for efficiency).


Maybe length is the wrong term, but it's perfectly reasonable to define an object's size the way it's done in this post.


Thanks for chiming in Daniel! Now I can see why Lodash chose size instead of length 😅

Notice also that JavaScript itself is choosing size for types like Set or Map: size is a more generic (and mathematical) name that suits more needs better, but nitpicking and pedantry aside, length is perfectly a understandable (and I keep using it for Sets and Maps until I remember that's wrong).

Clarifying meaning isn't pedantic.

Using size and capacity instead of length on data structures with dynamic lengths was done before JS.

There was probably a discussion somewhere, where they argued for/against both.

Python implements len() as a function with the magic method __len__ precisely to have one consistent way of retrieving an intuitive "length".


Totally fair assessment! I guess I always just associated length to the size, since length is the property being called for array or strings. So naturally when I was thinking of getting the size of an object, I automatically default to referring it to length as well 😅 I guess that's why Lodash opted for size and not length. This is probably the best thing with sharing an article. It always opens up a conversation. I'm glad you shared your comment! Now, I learned something. Thank you for explaining with such clarity! 😊


You're absolutely right. Semantics, to define the meaning of things, is great to have conversations about if you find the right people.

Meaning is flexible, after all, until something is defined. Exploring this creates new understanding and perspectives, which works wonders to break out of black/white thinking.

code of conduct - report abuse