Question

How to Get the Length of a JavaScript Object

javascriptobjectjavascript-objects

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:

Object.keys(user).length;

Why this works

  • Object.keys(user) returns an array of the object's own property names.
  • .length on that array gives the number of properties.
const user = {
  firstname: "Gareth",
  lastname: "Simpson",
  age: 21
};

console.log(Object.keys(user)); // ["firstname", "lastname", "age"]
console.log(Object.keys(user).length); // 3

Why this matters

Counting object properties is useful when:

  • checking whether an object is empty
  • validating incoming API data
  • summarizing configuration values
  • processing dynamic records

The important idea is this:

  • Arrays are ordered collections with a built-in length
  • Objects are key-value collections, so you usually count their keys instead

Mental Model

Think of an object as a set of labeled drawers.

  • Each property name is a drawer label, like firstname or age
  • 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
Take Quiz

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:

3

Check if an object is empty

const settings = {};

if (Object.keys(settings).length === 0) {
  console.log("Object is empty");
}

Alternative: count values or entries

Sometimes you may also see:

Object.values(myObject).length;
Object.entries(myObject).length;

These also return 3 for the example above, but Object.keys() is usually the clearest choice when your goal is to count properties.

Older loop-based approach

Before Object.keys() became the standard, developers often used a loop:

let count = 0;
for (const key in myObject) {
  if (Object.hasOwn(myObject, key)) {
    count++;
  }
}
console.log(count); // 3

This still works, but for most modern code, Object.keys(obj).length is simpler and easier to read.

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

  1. myObject is created with 3 properties:

    • firstname
    • lastname
    • age
  2. Object.keys(myObject) runs.

    • JavaScript looks at the object's own enumerable property names.
    • It creates a new array:
["firstname", "lastname", "age"]
  1. That array is stored in keys.

  2. keys.length is evaluated.

    • The array has 3 items.
    • So count becomes 3.
  3. The output is:

[ 'firstname', 'lastname', 'age' ]
3

Important detail

If the object had inherited properties from its prototype, Object.keys() would not include them. It only counts the object's own enumerable properties.

const parent = { country: "UK" };
const child = Object.create(parent);
child.firstname = "Gareth";

console.log(Object.keys(child)); // ["firstname"]
console.log(Object.keys(child).length); // 1

Even though child.country can be accessed, it is inherited, so it is not counted by Object.keys().

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: true
};

console.log(`Configured options: ${Object.keys(config).length}`);

4. Build summaries for reports

const scores = {
  math: 90,
  science: 85,
  english: 88
};

console.log(`Subjects recorded: ${Object.keys(scores).length}`);

5. Detect empty error collections

const errors = {};

if (Object.keys(errors).length === 0) {
  console.log("No validation errors");
}
Take Quiz

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 = {
  bio: "Developer",
  website: "example.com"
};

const filledFields = Object.keys(profile).length;
console.log(filledFields);

Working with transformed data

Objects are often created dynamically from arrays, form inputs, or API responses. After transformation, counting keys is a quick way to inspect the result.

const pairs = [
  ["firstname", "Gareth"],
  ["lastname", "Simpson"]
];

const result = Object.fromEntries(pairs);
console.log(Object.keys(result).length); // 2

When teams choose Map instead

If a codebase frequently needs size tracking, insertion order behavior, and dynamic key management, developers may use Map instead of a plain object:

const userMap = new Map();
userMap.set("firstname", "Gareth");
userMap.set("lastname", "Simpson");

console.log(userMap.size); // 2

That is often a sign that the data structure matters as much as the count.

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";

let count = 0;
for (const key in child) {
  count++;
}

console.log(count); // May include inherited properties

Problem: for...in iterates over enumerable properties, including inherited ones.

Fix: Check ownership.

let count = 0;
for (const key in child) {
  if (Object.hasOwn(child, key)) {
    count++;
  }
}

Mistake 3: Confusing empty values with missing properties

const user = {
  firstname: "",
  age: null
};

console.log(Object.keys(user).length); // 2

Even though the values are empty-like, the properties still exist, so they are counted.

Mistake 4: Counting nested properties incorrectly

const user = {
  name: {
    first: "Gareth",
    last: "Simpson"
  },
  age: 21
};

console.log(Object.keys(user).length); // 2

This counts only the top-level keys: name and age.

If you need a deep count, that is a different problem.

Mistake 5: Using objects when Map is a better fit

If you need frequent size checks and dynamic keys, a Map may be more appropriate:

const data = new Map();
data.set("a", 1);
data.set("b", 2);

console.log(data.size); // 2

Comparisons

ConceptPlain ObjectArrayMap
Main purposeKey-value dataOrdered list of itemsKey-value data structure
Built-in size propertyNo .lengthYes, .lengthYes, .size
Standard way to countObject.keys(obj).lengtharr.lengthmap.size
Key typeUsually strings or symbolsNumeric indexesAny value
Best forStructured records, configs, JSON-like dataLists and sequencesDynamic collections with frequent adds/removes

Object.keys() vs for...in

ApproachWhat it doesProsCons
Object.keys(obj).lengthCounts own enumerable keysSimple, readable, standardCreates an array
for...inLoops through enumerable keys, including inherited onesFlexibleMust filter inherited properties

Object vs Map for counting

If your main question is, "How many entries are there?" often and repeatedly, Map can be more direct because it has a built-in .size.

const obj = { a: 1, b: 2 };
console.log(Object.keys(obj).length); // 2

const map = new Map([
  ["a", 1],
  ["b", 2]
]);
console.log(map.size); // 2
Take Quiz

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 .length property.
  • Object.keys(obj) returns an array of the object's own enumerable keys.
  • .length works on that returned array, not on the object itself.
  • for...in includes inherited enumerable properties unless you filter them.
  • If you need built-in size tracking for key-value data, consider Map.

Common checks

// Empty object?
if (Object.keys(obj).length === 0) {
  // empty
}

// Safe manual count with for...in
let count = 0;
for (const key in obj) {
  if (Object.hasOwn(obj, key)) {
    count++;
  }
}

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?

No. It only counts the top-level keys of the object you pass in.

Can I use for...in to count properties?

Yes, but you should filter inherited properties with Object.hasOwn() or a similar check.

Take Quiz

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

  1. Create a function that accepts a plain object.
  2. Return the number of the object's own enumerable properties.
  3. Print whether the object is empty or not.
  4. Test the function with at least three different objects.
  5. Include one example with nested data to show that only top-level keys are counted.
Take Quiz

Keep learning

Related questions

View more