Explain Codes LogoExplain Codes Logo

Length of a JavaScript object

javascript
object-properties
javascript-utility-functions
property-counting
Anton ShumikhinbyAnton Shumikhin·Aug 25, 2024
TLDR

Use Object.keys(obj).length to quickly count properties in a JavaScript object, giving you the total number of enumerable keys.

const quickSize = Object.keys({ a: 1, b: 2 }).length; // 2 - "Who needs a freeway when you have a shortcut ⚡"

But for all properties, including non-enumerable and symbol-keyed:

const totalProperties = Object.getOwnPropertyNames(obj).length + Object.getOwnPropertySymbols(obj).length;

All-inclusive property count

Accounting for non-enumerable properties

Use Object.getOwnPropertyNames() to count non-enumerable properties:

const obj = { a: 1 }; // Making 'b' shy 🙈 Object.defineProperty(obj, 'b', { value: 2, enumerable: false }); const totalSize = Object.getOwnPropertyNames(obj).length; // 2 - "Even the shy ones count! 🎭"

Don't forget symbol-keyed properties

To count symbol-keyed properties, use Object.getOwnPropertySymbols(). Symbols are the wallflowers at the property party 🎉:

const symbolKey = Symbol('key'); // Our 'key' symbol 🔑 const obj = { [symbolKey]: 3 }; const symbolCount = Object.getOwnPropertySymbols(obj).length; // 1 - "Counting the wallflowers too 🕵️‍♀️"

Using both getOwnPropertyNames() and getOwnPropertySymbols(), we count all properties:

const totalSize = totalSize + symbolCount; // "Everyone's invited to the party 🎈"

Object extensions: handle with care!

Avoid extending Object.prototype to circumvent conflicts and unwanted surprises with enumeration. Instead, attach methods directly to Object:

Object.size = function(obj) { return Object.getOwnPropertyNames(obj).length + Object.getOwnPropertySymbols(obj).length; };

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:

if (obj !== null && typeof obj === 'object') { const size = Object.keys(obj).length // "No objections here, boss! 🧐" }

Only the originals, please!

Use a for-in loop with hasOwnProperty for a precise count, excluding inherited properties:

let count = 0; for (let key in obj) { if (obj.hasOwnProperty(key)) count++; // "No gate-crashers allowed! 🛑" }

Legacy browser support: Who got left behind!

For older browsers, provide a polyfill for Object.keys(), ensuring universal support:

if (!Object.keys) { Object.keys = function(obj) { var keys = [], property; for (property in obj) { if (Object.prototype.hasOwnProperty.call(obj, property)) { keys.push(property); // "We don't leave anyone behind! 🧓" } } return keys; }; }

Incorporating functional programming

Library to the rescue: Underscore.js

For a functional programming style, external libraries like Underscore.js can come handy:

const size = _.size({ a: 1, b: 2, c: 3 }); // 3 - "Underscore, always there to lend a hand 🤝"

jQuery plugins: Making life easier!

A custom jQuery plugin can do the counting:

$.assocArraySize = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; // "Counting made fun with jQuery 🎊" } return size; };

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.