Emmanuel Akinfulubi

JavaScriptObject

Count the properties of an object in JavaScript

Beginner · 3 min read

Arrays tell you their size with length. Objects don't. Yet you often need to know how many fields an object has: to check a settings object isn't empty, to show "3 filters applied", or to compare two records quickly.

In this tutorial you will count the properties of a student object. You will learn the usual one-line answer, and then see exactly which properties it counts and which it quietly ignores. You need to know what an object and an array are.

Why objects have no length

length belongs to arrays and strings. On a plain object it is just a key that doesn't exist, so reading it gives undefined:

JavaScript

const student = { name: 'David Rayy', sclass: 'VI', rollno: 12 };
console.log(student.length); // undefined

The fix is to turn the keys into an array, then ask the array.

Not every property is visible

Every property has a few settings. One of them is enumerable: whether the property shows up when you list an object's keys. Properties you create normally are enumerable. Built-in ones, and ones you make with Object.defineProperty, are usually not. A non-enumerable property still works when you read it. It just stays out of lists.

Keys can also be symbols instead of strings. A symbol is a unique value made with Symbol('label'). It is often used as a key that won't clash with any other.

Here is the exercise. Try it first if you like, or build it with us below.

3 How many properties does an object have?

easy

Objects have no length. Count their properties, and be clear about which properties you are counting.

Stuck? Three hints, smallest first
  1. 1. Object.keys(obj).length is the usual answer.
  2. 2. It counts own enumerable string keys only — not inherited, not symbols, not hidden ones.
  3. 3. Object.getOwnPropertyNames includes non-enumerable keys; Reflect.ownKeys includes symbols too.

Step 1: count with Object.keys

Object.keys gives an array of keys, and arrays have length:

Step 1

const size = (obj) => Object.keys(obj).length;
console.log(size(student)); // 3
console.log(size({}));      // 0

For everyday objects, that is the answer. The rest of this lesson is about what "everyday" means.

Step 2: add a hidden property

Make an object with one normal property, then add a non-enumerable one with Object.defineProperty:

Step 2

const mixed = { visible: 1 };
Object.defineProperty(mixed, 'hidden', { value: 2, enumerable: false });
console.log(mixed.hidden);        // 2
console.log(Object.keys(mixed));  // [ 'visible' ]
console.log(JSON.stringify(mixed)); // {"visible":1}

mixed.hidden reads fine, but Object.keys and JSON.stringify both skip it. Object.getOwnPropertyNames is the method that includes non-enumerable keys:

JavaScript

console.log(Object.getOwnPropertyNames(mixed)); // [ 'visible', 'hidden' ]

Step 3: add a symbol key

Now give the same object a symbol key:

Step 3

mixed[Symbol('tag')] = 3;
console.log(Object.keys(mixed).length);                // 1
console.log(Object.getOwnPropertyNames(mixed).length); // 2
console.log(Reflect.ownKeys(mixed).length);            // 3

That gives three levels of counting. Object.keys counts enumerable string keys. Object.getOwnPropertyNames adds the hidden ones. Reflect.ownKeys adds symbols too, so it counts everything the object holds itself.

Step 4: inherited properties are never counted

Make an object that inherits from mixed with Object.create, and give it one property of its own:

Step 4

const inheriting = Object.create(mixed);
inheriting.own = 4;
console.log(size(inheriting));  // 1
console.log(inheriting.visible); // 1

inheriting can read visible, but it borrows it from mixed, so it is not counted. All three methods above only look at the object's own properties.

Step 5: when you need a size, consider a Map

A Map is a collection built for key-value pairs, and it keeps its own count in size:

Step 5

console.log(new Map([['a', 1], ['b', 2]]).size); // 2
console.log(new Map([[1, 'a'], ['1', 'b']]).size); // 2

The second line has two keys, the number 1 and the string '1'. A Map keeps them apart. A plain object would turn both into the string '1' and end up with one key.

The full solution

The panel defines size, builds the mixed object with a normal, a hidden and a symbol property, and prints all three counts side by side. Press Run to compare them.

The answer

const student = { name: 'David Rayy', sclass: 'VI', rollno: 12 };

const size = (obj) => Object.keys(obj).length;

// An object with one of each kind of property, to show what each count includes.
const mixed = { visible: 1 };
Object.defineProperty(mixed, 'hidden', { value: 2, enumerable: false });
mixed[Symbol('tag')] = 3;
const inheriting = Object.create(mixed);
inheriting.own = 4;

console.log('size(student):', size(student), ' (objects have no .length:', student.length, ')');
console.log('--- the three levels of counting ---');
console.log('Object.keys              :', Object.keys(mixed), '-> enumerable string keys');
console.log('Object.getOwnPropertyNames:', Object.getOwnPropertyNames(mixed), '-> plus non-enumerable');
console.log('Reflect.ownKeys          :', Reflect.ownKeys(mixed).map(String), '-> plus symbols');
console.log('a Map does have .size    :', new Map([['a', 1]]).size);

Output


      
13 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 13 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

13 checks

test("the example object has 3 properties", size(student), 3);
test('an object has no length property', student.length, undefined);
test('an empty object has 0', size({}), 0);
test('keys counts only enumerable string keys', Object.keys(mixed).length, 1);
test('getOwnPropertyNames also counts the hidden one', Object.getOwnPropertyNames(mixed).length, 2);
test('ownKeys also counts the symbol', Reflect.ownKeys(mixed).length, 3);
test('the hidden property is still readable', mixed.hidden, 2);
test('it is just not enumerable', Object.keys(mixed).includes('hidden'), false);
test('inherited properties are not counted', size(inheriting), 1);
test('even though they are readable', inheriting.visible, 1);
test('JSON.stringify also skips the hidden one', JSON.stringify(mixed), '{"visible":1}');
test('a Map reports its size directly', new Map([['a', 1], ['b', 2]]).size, 2);
test('and counts every key type', new Map([[1, 'a'], ['1', 'b']]).size, 2);

Object.keys(obj).length is right, provided you know it counts own enumerable string keys and nothing else. The three-way comparison above is the point: a non-enumerable property is fully readable but invisible to Object.keys, to for...in and to JSON.stringify. That last assertion about Map is a reminder too — new Map([[1, 'a'], ['1', 'b']]) has size 2, because a Map keeps 1 and '1' apart, while a plain object would convert both keys to the string '1' and keep only one.

Common mistakes

  • Writing obj.length. Plain objects don't have it, so you get undefined, and undefined > 0 is false. Use Object.keys(obj).length.
  • Expecting hidden properties to be counted. Object.keys skips non-enumerable keys. Use Object.getOwnPropertyNames if you need them.
  • Forgetting symbol keys. Only Reflect.ownKeys sees them.

Try it yourself

  1. Write isEmpty(obj) that returns true for {} and false for { a: 1 }.
  2. Count the own property names of Math with Object.keys and with Object.getOwnPropertyNames. Why is the first one 0?
  3. Build a Map from Object.entries(student) and print its size.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.