How to count the number of properties in a JavaScript object

By

Learn how to count the number of properties in a JavaScript object using Object.keys() to get an array of its enumerable keys and reading the length property.

~~~

To count the number of properties in a JavaScript object, pass the object to Object.keys() and read the length property of the array you get back:

const car = {
  color: 'Blue',
  brand: 'Ford',
  model: 'Fiesta'
}

Object.keys(car).length //3

Object.keys() returns an array containing all the keys of the object:

Object.keys(car) //['color', 'brand', 'model']

Since that’s a regular array, we can check how many items it contains with length. That number is the number of properties.

Which properties get counted?

Object.keys() only returns the own enumerable properties of the object.

Own means the property is defined directly on the object. Properties inherited from the prototype are not included. This is usually what you want: when you count the properties of car, you don’t want toString() and the other methods every object inherits to show up in the count.

Enumerable means the property’s internal enumerable flag is set to true. That’s the default when you create a property with an object literal or a plain assignment, so in everyday code every property you add is counted. Properties defined with Object.defineProperty() can opt out of enumeration, and those won’t appear. Check MDN for more info on this subject.

Watch out for Symbol keys

There is one case where the count can look lower than you expect: properties keyed by a Symbol.

const id = Symbol('id')

const user = {
  name: 'Flavio',
  [id]: 123
}

Object.keys(user).length //1

The object has two properties, but Object.keys() ignores the symbol-keyed one, so the count is 1.

If you need to include symbols, count them separately with Object.getOwnPropertySymbols() and add the two lengths:

Object.keys(user).length +
  Object.getOwnPropertySymbols(user).length //2

Symbol keys are rare in everyday code, so Object.keys(obj).length is the answer in almost every situation. But when a count doesn’t add up, this is the first thing I’d check.

~~~

Related posts about js: