is there a built-in or accepted best practice way to get the length of this object?
The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be:
Here's an update as of 2016 and widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers, we can use Object.keys() so the above code just becomes:
var size = Object.keys(myObj).length;
This doesn't have to modify any existing prototype since Object.keys() is now built in.
If we know we don't have to worry about hasOwnProperty checks, we can do this very simply:
Updated: If you're using Underscore.js (recommended, it's lightweight!), then we can just do
Use something as simple as:
It doesn't have to be difficult and definitely doesn't require another function to accomplish.
Here's the most cross-browser solution.
This is better than the accepted answer because it uses native Object.keys if exists. Thus, it is the fastest for all modern browsers.