How to get the number of properties in a JavaScript object without looping#

Unlike arrays, JavaScript objects do not a have a length property which gives you the number of properties / items in an object. The most common way of getting the number of properties is to loop through the object - not pretty, resource intensive.

This has been a long known problem JavaScript developers have been facing. All modern and superior browsers support a fix for this annoying problem - Object.keys(). However, inferior browsers such as Internet Explorer are known not to support such useful features.

Run
Clear

Cool? The Object.keys() static method accepts an objects and returns an array of natively defined keys of the objects, those which pass the hasOwnProperty() test. Just count the length of the returned array, and you have the size of the object / number of items or properties in the object."

Reference#

  1. MDN - Object​.keys()
Tweet this | Share on LinkedIn |