Length of a JavaScript object
Use Object.keys(obj).length
to quickly count properties in a JavaScript object, giving you the total number of enumerable keys.
But for all properties, including non-enumerable and symbol-keyed:
All-inclusive property count
Accounting for non-enumerable properties
Use Object.getOwnPropertyNames()
to count non-enumerable properties:
Don't forget symbol-keyed properties
To count symbol-keyed properties, use Object.getOwnPropertySymbols()
. Symbols are the wallflowers at the property party 🎉:
Using both getOwnPropertyNames()
and getOwnPropertySymbols()
, we count all properties:
Object extensions: handle with care!
Avoid extending Object.prototype
to circumvent conflicts and unwanted surprises with enumeration. Instead, attach methods directly to Object
:
This allows for easy total property count: Object.size(obj)
. "It doesn't get much simpler than this! 😉
Comprehensive coverage
Object validation: Safety first!
Ensure obj
is indeed an object before counting, else Object.keys()
might raise a fuss:
Only the originals, please!
Use a for-in loop with hasOwnProperty
for a precise count, excluding inherited properties:
Legacy browser support: Who got left behind!
For older browsers, provide a polyfill for Object.keys()
, ensuring universal support:
Incorporating functional programming
Library to the rescue: Underscore.js
For a functional programming style, external libraries like Underscore.js can come handy:
jQuery plugins: Making life easier!
A custom jQuery plugin can do the counting:
Ruling out confusion
Unlike arrays, JavaScript objects don't come with a built-in length
property. When measuring an object's size, we count the properties it contains.
Code snippets: Making every line count
We've covered varying methods to measure object length, from core utilities to polyfills and library functions. You're now equipped with a versatile toolkit for almost any scenario.
Was this article helpful?