How to get the length of a JavaScript object?
What is the best practice method to determine the number of properties in a JavaScript object? I’m looking for a built-in solution or standard approach to get the length/count of properties in an object.
Example object:
const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
The best way to get the length of a JavaScript object (count its properties) is using Object.keys(obj).length, which returns an array of the object’s own enumerable property names and then gets the array’s length. This method is simple, efficient, and works consistently across all modern JavaScript environments.
Contents
- Understanding JavaScript Objects
- Built-in Methods for Counting Properties
- Comparing Different Approaches
- Best Practices and Considerations
- Practical Examples
- Edge Cases and Special Scenarios
Understanding JavaScript Objects
JavaScript objects are collections of properties, where each property is a key-value pair. Unlike arrays, objects don’t have a built-in length property that directly gives you the count of properties. This fundamental difference causes confusion for developers coming from other programming languages.
In JavaScript, objects can have:
- Own properties: Properties directly defined on the object
- Inherited properties: Properties from the object’s prototype chain
- Enumerable properties: Properties that can be iterated over
- Non-enumerable properties: Hidden properties that don’t appear in normal iteration
When counting properties, you typically want to count only the object’s own properties, not inherited ones, and whether you want to include non-enumerable properties depends on your use case.
Built-in Methods for Counting Properties
Object.keys() Method
The most common and recommended approach is using Object.keys():
const myObject = {
firstname: "Gareth",
lastname: "Simpson",
age: 21
};
const propertyCount = Object.keys(myObject).length;
console.log(propertyCount); // Output: 3
Object.keys() returns an array of the object’s own enumerable property names, making it perfect for counting typical object properties.
Object.getOwnPropertyNames() Method
For counting all own properties (including non-enumerable ones):
const myObject = {
firstname: "Gareth",
lastname: "Simpson",
age: 21
};
const allPropertiesCount = Object.getOwnPropertyNames(myObject).length;
console.log(allPropertiesCount); // Output: 3
This method includes properties like toString, valueOf, etc., if they’re defined directly on the object.
Reflect.ownKeys() Method
The modern approach that includes all own properties:
const myObject = {
firstname: "Gareth",
lastname: "Simpson",
age: 21
};
const allKeysCount = Reflect.ownKeys(myObject).length;
console.log(allKeysCount); // Output: 3
Reflect.ownKeys() is similar to Object.getOwnPropertyNames() but provides a more consistent API.
Comparing Different Approaches
Performance Comparison
| Method | Performance | What It Counts | Browser Support |
|---|---|---|---|
Object.keys() |
Fastest | Own enumerable properties | ES5+ |
Object.getOwnPropertyNames() |
Fast | Own enumerable + non-enumerable | ES5+ |
Reflect.ownKeys() |
Fast | All own properties (including symbols) | ES6+ |
| For…in loop | Slowest | Enumerable properties (including inherited) | ES1+ |
When to Use Each Method
- Use
Object.keys().lengthwhen you need to count standard, enumerable properties (90% of cases) - Use
Object.getOwnPropertyNames().lengthwhen you need to count all own properties, including non-enumerable ones - Use
Reflect.ownKeys().lengthwhen you need to count all properties including symbol keys - Avoid For…in loops for counting unless you specifically need to include inherited enumerable properties
Best Practices and Considerations
Recommended Approach
The best practice is to use Object.keys(obj).length because:
- Clear and readable: It clearly expresses the intent to count properties
- Efficient: It’s optimized for performance in modern JavaScript engines
- Predictable: It consistently counts only own enumerable properties
- Widely supported: Works in all modern browsers and Node.js environments
Performance Considerations
For objects with very large numbers of properties, the performance difference becomes noticeable:
// For very large objects (10,000+ properties)
const largeObject = {};
for (let i = 0; i < 10000; i++) {
largeObject[`prop${i}`] = i;
}
// Object.keys() is generally the fastest for typical use cases
const count = Object.keys(largeObject).length;
Symbol Properties
If your object has symbol properties, Object.keys() won’t count them:
const myObject = {
firstname: "Gareth",
[Symbol('id')]: 12345
};
console.log(Object.keys(myObject).length); // Output: 1 (doesn't count symbols)
console.log(Object.getOwnPropertySymbols(myObject).length); // Output: 1 (only symbols)
console.log(Reflect.ownKeys(myObject).length); // Output: 2 (both strings and symbols)
Practical Examples
Basic Object Property Counting
const user = {
name: "John Doe",
email: "john@example.com",
age: 30,
isActive: true
};
// Count properties
const propertyCount = Object.keys(user).length;
console.log(`User object has ${propertyCount} properties`);
// Output: User object has 4 properties
Dynamic Property Counting
class DataStore {
constructor() {
this.data = {};
}
set(key, value) {
this.data[key] = value;
return this.getItemCount();
}
getItemCount() {
return Object.keys(this.data).length;
}
getItems() {
return Object.keys(this.data);
}
}
const store = new DataStore();
store.set('name', 'Alice');
store.set('age', 25);
store.set('city', 'New York');
console.log(store.getItemCount()); // Output: 3
console.log(store.getItems()); // Output: ['name', 'age', 'city']
Filtering Properties Before Counting
const person = {
name: "Bob",
age: 28,
password: "secret123",
email: "bob@example.com"
};
// Count only non-sensitive properties
const safeProperties = Object.keys(person).filter(key => key !== 'password');
const safeCount = safeProperties.length;
console.log(safeCount); // Output: 3
Edge Cases and Special Scenarios
Null and Undefined Objects
Always check for null or undefined objects:
function getPropertyCount(obj) {
if (obj === null || obj === undefined) {
return 0;
}
return Object.keys(obj).length;
}
console.log(getPropertyCount(null)); // Output: 0
console.log(getPropertyCount(undefined)); // Output: 0
Arrays as Objects
Remember that arrays are objects in JavaScript:
const myArray = [1, 2, 3, 4, 5];
console.log(Object.keys(myArray).length); // Output: 5
console.log(myArray.length); // Output: 5
// But be careful with sparse arrays
const sparseArray = [];
sparseArray[10] = 'value';
console.log(Object.keys(sparseArray).length); // Output: 1
console.log(sparseArray.length); // Output: 11
Objects with Inherited Properties
const parent = {
inheritedProp: 'value'
};
const child = Object.create(parent);
child.ownProp = 'another value';
// For...in includes inherited properties
let countForIn = 0;
for (const key in child) {
if (child.hasOwnProperty(key)) {
countForIn++;
}
}
console.log(countForIn); // Output: 1
// Object.keys() only counts own properties
console.log(Object.keys(child).length); // Output: 1
Objects with Prototype Methods
function User(name) {
this.name = name;
}
User.prototype.greet = function() {
return `Hello, ${this.name}`;
};
const user = new User('Alice');
console.log(Object.keys(user).length); // Output: 1 (only 'name')
console.log(Object.getOwnPropertyNames(user).length); // Output: 1 (still only 'name')
console.log(Object.getOwnPropertyNames(User.prototype).length); // Output: 1 ('greet')
Conclusion
- The best practice for counting JavaScript object properties is using
Object.keys(obj).length, which efficiently counts only the object’s own enumerable properties - Choose the right method based on your needs:
Object.keys()for standard properties,Object.getOwnPropertyNames()for including non-enumerable properties, andReflect.ownKeys()for symbol properties - Always validate your input objects to handle null or undefined cases gracefully
- Consider performance when working with very large objects, though
Object.keys()is generally optimal for most use cases - Remember that arrays are objects, but
array.lengthandObject.keys(array).lengthcan differ with sparse arrays
For the example object provided, simply use Object.keys(myObject).length to get the count of 3 properties.