Get a free trial // Grow your CSS skills // Land your dream job

Get Object Size

Last updated on:

As in, the number of keys.

function objectSize(the_object) {
  /* function to validate the existence of each key in the object to get the number of valid keys. */
  var object_size = 0;
  for (key in the_object){
    if (the_object.hasOwnProperty(key)) {
  return object_size;


// Arbitrary object
var something = {
  dog: "cat",
  cat: "dog"

// Logs: 2


  1. code200
    Permalink to comment#

    Be sure to add var in front of key in your loop:

    for (var key in the_object){

    so the variable key goes out of scope with the function.

    Most recent browsers support this shorter version:
  2. Dwight Vietzke
    Permalink to comment#

    Just ran across this post while debugging code for IE. IE versions before 9 seem to have a problem with Object.keys and .hasOwnProperty used directly on an object. So a more sophisticated replacement is necessary, which can be found here:

    Hope this helps.

  3. Sam Purcell
    Permalink to comment#

    I like this Chris, but it seems more correct to add it to the Object prototype. IE

    Object.prototype.size = function() {
    var size = 0
    // your code, but using "this"

    return size;
    Called with something.size()

    From what I understand, adding a new function to the object prototype should not be a problem.

    • Michael Caputo
      Permalink to comment#

      Hey Sam, could you write out your suggestion? I’m a bit confused by this.

      Thanks for the help.

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

There's a whole bunch of content on CSS-Tricks.

Search for Stuff   •   Browse the Archives

Get the Newsletter ... or get the RSS feed