How to get the size of an object in JavaScript#

Arrays in JavaScript have a length property that gives you the number of items in an array. Objects on the other hand, don't have a length or size property.

var myArray = ['A', 'B'];
var myObject = {a:1, b:2, c:2};
Run
Clear

The old method of counting the number of properties in an object involved looping through the object properties and incrementing a counter:

Run
Clear

The new and efficient method of getting the object size involves using the Object.keys() method:

Run
Clear

Isn't it much better? Needless to say, Object.keys() returns an array of all the properties of an object. Think of its other possible uses.

References#

  1. MDN - Object​.keys()
  2. MDN - Array.length