Question
I have a JavaScript object and want to know how to get its length.
Is there a built-in or widely accepted best-practice way to count how many properties the object has?
const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
Short Answer
By the end of this page, you will understand that plain JavaScript objects do not have a built-in .length property like arrays do. You will learn the standard way to count an object's properties, when to use Object.keys(), how inherited properties affect counting, and what patterns developers use in real code.
Concept
In JavaScript, a plain object stores data as key-value pairs.
const user = {
firstname: "Gareth",
lastname: "Simpson",
age: 21
};
A common beginner assumption is that objects have a .length property, similar to arrays:
const numbers = [10, 20, 30];
console.log(numbers.length); // 3
But plain objects do not track their size with a built-in .length property:
const user = { firstname: "Gareth", lastname: "Simpson", age: 21 };
console.log(user.length); // undefined
To count the number of an object's own enumerable properties, the standard approach is:
Mental Model
Think of an object as a set of labeled drawers.
- Each property name is a drawer label, like
firstnameorage - Each property value is what is stored in that drawer
An array is more like a row of numbered boxes, so JavaScript can easily say how many boxes there are using .length.
An object is not organized by numeric positions, so JavaScript does not keep a simple built-in counter called .length for it. Instead, if you want to know how many drawers exist, you ask for the list of drawer labels:
Object.keys(myObject)
Then you count that list.
So the mental shortcut is:
- Array length = count the boxes
- Object length = count the keys
Syntax and Examples
The most common way to count properties in a plain object is:
Object.keys(object).length
Example
const myObject = {
firstname: "Gareth",
lastname: "Simpson",
age: 21
};
const count = Object.keys(myObject).length;
console.log(count); // 3
How it works
Object.keys(myObject);
returns:
["firstname", "lastname", "age"]
Then:
Object.keys(myObject).length;
returns:
Step by Step Execution
Consider this example:
const myObject = {
firstname: "Gareth",
lastname: "Simpson",
age: 21
};
const keys = Object.keys(myObject);
const count = keys.length;
console.log(keys);
console.log(count);
Step by step
-
myObjectis created with 3 properties:firstnamelastnameage
-
Object.keys(myObject)runs.- JavaScript looks at the object's own enumerable property names.
- It creates a new array:
["firstname", "lastname", "age"]
Real World Use Cases
Counting object properties appears in many practical situations.
1. Validate request data
You may want to reject empty request bodies in an API:
const requestBody = {};
if (Object.keys(requestBody).length === 0) {
console.log("Request body is empty");
}
2. Check whether filters were provided
A search form may generate a filters object:
const filters = {
category: "books",
priceMax: 20
};
if (Object.keys(filters).length > 0) {
console.log("Apply filters");
}
3. Count dynamic configuration options
const config = {
darkMode: true,
notifications: false,
autoSave:
};
.();
Real Codebase Usage
In real projects, developers usually do more than just count properties once. They use this concept in patterns like validation, guard clauses, and data handling.
Guard clause for empty objects
A common pattern is to return early if there is nothing to process:
function processFilters(filters) {
if (Object.keys(filters).length === 0) {
return "No filters provided";
}
return "Processing filters...";
}
Validation before saving data
function saveUserUpdates(updates) {
if (Object.keys(updates).length === 0) {
throw new Error("No updates to save");
}
console.log("Saving", updates);
}
Counting optional fields
const profile = {
: ,
:
};
filledFields = .(profile).;
.(filledFields);
Common Mistakes
Mistake 1: Expecting .length on a plain object
const user = { firstname: "Gareth", lastname: "Simpson" };
console.log(user.length); // undefined
Why it happens: Arrays have .length, so beginners expect objects to have it too.
Fix: Use Object.keys(user).length.
console.log(Object.keys(user).length); // 2
Mistake 2: Using for...in without filtering inherited properties
Broken example:
const parent = { country: "UK" };
const child = Object.create(parent);
child.firstname = "Gareth";
count = ;
( key child) {
count++;
}
.(count);
Comparisons
| Concept | Plain Object | Array | Map |
|---|---|---|---|
| Main purpose | Key-value data | Ordered list of items | Key-value data structure |
| Built-in size property | No .length | Yes, .length | Yes, .size |
| Standard way to count | Object.keys(obj).length | arr.length | map.size |
| Key type | Usually strings or symbols | Numeric indexes | Any value |
| Best for | Structured records, configs, JSON-like data |
Cheat Sheet
// Count properties in a plain object
Object.keys(obj).length
// Example
const user = { firstname: "Gareth", lastname: "Simpson", age: 21 };
console.log(Object.keys(user).length); // 3
// Check if object is empty
Object.keys(obj).length === 0
// Get property names
Object.keys(obj)
// Get property values
Object.values(obj)
// Get key-value pairs
Object.entries(obj)
Rules to remember
- Plain objects do not have a
.lengthproperty. Object.keys(obj)returns an array of the object's own enumerable keys..lengthworks on that returned array, not on the object itself.
FAQ
How do I get the length of a JavaScript object?
Use Object.keys(obj).length to count the object's own enumerable properties.
Why does myObject.length return undefined?
Because plain objects do not have a built-in .length property. That property exists on arrays, not regular objects.
Is Object.keys(obj).length the standard way?
Yes. It is the most common and readable way to count properties on a plain object in modern JavaScript.
Does Object.keys() count inherited properties?
No. It only counts the object's own enumerable properties.
How do I check if an object is empty?
Use:
Object.keys(obj).length === 0
Should I use Map instead of an object?
Use Map if you need key-value storage with a built-in .size, dynamic keys, or frequent add/remove operations.
Does Object.keys() count nested object properties too?
Mini Project
Description
Build a small utility that counts the number of properties in different JavaScript objects and reports whether each object is empty. This demonstrates the standard object-counting pattern and helps you practice the difference between objects and arrays.
Goal
Create a reusable function that returns the number of own properties in a plain object and test it with multiple examples.
Requirements
- Create a function that accepts a plain object.
- Return the number of the object's own enumerable properties.
- Print whether the object is empty or not.
- Test the function with at least three different objects.
- Include one example with nested data to show that only top-level keys are counted.
Keep learning
Related questions
Adding Table Rows with jQuery: append(), Limits, and Best Practices
Learn how to add table rows in jQuery using append(), what elements are allowed in tables, and safer ways to build rows dynamically.
Bower vs npm: What’s the Difference in JavaScript Package Management?
Learn the plain difference between Bower and npm, how each manages packages, and why npm replaced Bower in most JavaScript projects.
Can `(a == 1 && a == 2 && a == 3)` Ever Be True in JavaScript?
Learn how JavaScript type coercion, loose equality, and custom object conversion can make `a == 1 && a == 2 && a == 3` true.