To get the length (number of properties) of a JavaScript object, you can use one of these methods:
1. Using Object.keys()
(ES6+ Recommended)
Convert the object’s keys to an array and get its length:
const obj = { a: 1, b: 2, c: 3 };
const length = Object.keys(obj).length; // 3
2. Using a Loop (Legacy Approach)
Loop through the object’s properties and count them:
function getObjectLength(obj) {
let count = 0;
for (const key in obj) {
if (obj.hasOwnProperty(key)) { // Exclude inherited properties
count++;
}
}
return count;
}
const obj = { x: 10, y: 20 };
console.log(getObjectLength(obj)); // 2
3. Using Object.getOwnPropertyNames()
(Includes Non-Enumerable Properties)
Get all own properties (even non-enumerable ones):
const obj = Object.create({}, {
a: { value: 1, enumerable: true },
b: { value: 2, enumerable: false }
});
const length = Object.getOwnPropertyNames(obj).length; // 2
Key Notes:
Object.keys()
returns only enumerable own properties.for...in
loops include inherited enumerable properties unless filtered withhasOwnProperty
.Object.getOwnPropertyNames()
includes all own properties (enumerable and non-enumerable).- Symbol keys are ignored in all methods above. Use
Object.getOwnPropertySymbols()
to include them:
const sym = Symbol('key');
const obj = { [sym]: 'value', a: 1 };
const totalKeys = Object.keys(obj).length + Object.getOwnPropertySymbols(obj).length; // 2
Edge Cases:
- If the object is
null
orundefined
, wrap it in a check:
const obj = null;
const length = obj ? Object.keys(obj).length : 0; // 0
Example Workflow:
const user = { name: "Alice", age: 30, role: "Admin" };
console.log(Object.keys(user).length); // 3
// Add a non-enumerable property
Object.defineProperty(user, 'id', { value: 123, enumerable: false });
console.log(Object.keys(user).length); // 3 (still)
console.log(Object.getOwnPropertyNames(user).length); // 4
Use Object.keys()
for most cases, and fall back to loops or Object.getOwnPropertyNames()
for specialized scenarios.