Javascript Function for Finding an Object’s Properties

May 19, 2008

This function makes use of Douglas Crockford‘s functions available from his Remedial Javascript page. If you haven’t read his series of articles on Javascript, you’re missing out. Also, check out the Yahoo User Interface team’s website and the YUI blog for more Javascript info and tips.

Crockford’s isEmpty function:

function isEmpty(o) {
    var i, v;
    if (typeOf(o) === 'object') {
        for (i in o) {
            v = o[i];
            if (v !== undefined && typeOf(v) !== 'function') {
                return false;
    return true;

As a question to the readers, how should the isEmpty function treat object properties that are undefined or functions? Currently, the function ignores undefined properties and functions. Should it count them as properties?

My getProperties function looks much like the isEmpty function and uses the same method for accessing an object’s properties. Rather than return true or false based on the existence of properties, this function returns an array of all of the property names for the given object. A trivial modification of the isEmpty function, but useful none the less.

function getProperties(obj) {
  var i, v;
  var count = 0;
  var props = [];
  if (typeof(obj) === 'object') {
    for (i in obj) {
      v = obj[i];
      if (v !== undefined && typeof(v) !== 'function') {
        props[count] = i;
  return props;

3 Responses to “Javascript Function for Finding an Object’s Properties”

  1. Very interesting, thanks. Javascript could really do with a native function that lets you perform an Object.length in the same way as you can an array.length.

    Just as an aside, in the getProperties function, couldn’t you get rid of the count variable and just say:

    props[props.length] = i;


  2. fitzthegreat Says:

    Thanks for the comments!

    That’s an interesting idea using props.length as the array index. Wouldn’t that result in every property being assigned to the same index of props[props.length] ?

  3. Prabin Says:

    Nice one. It really helped me out.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: