JavaScript function for logging the members of an object (with horizontal alignment) When iterating over the members of an object for logging the keys / values one gets a "stair case" effect.
Therefore I wrote myself this function which takes care for a left-alignment of the values.

Any hints concerning flaws and improvement-recommendations welcome.



// #### START TEST #######################
var person = {
  yourMobilPhoneNumber : 01234171819,
  firstName : 'theFirstName',
  lastName : 'theLastName',
  mail : 'myEmail@abc.com',
  zip : '12345',          
  street : 'theNameOfMyStreet',
  city : 'someCitySomewhere',
  yourVeryPersonalWebpage : 'http://that-is-me.com',
  id : 12345,
  calculate: function() { return 3 + 4; }
};

displayMembers(person);
// #### END TEST #######################

// Displays the members of an assigned 
//   object on the console.

// -- Parameter -------------
// Object - An object which members 
//   shall be displayed.

function displayMembers(obj) {
  var i;
  var max = (function() {
    var ret = 0;
    var keys = Object.keys(obj);

    for (i = 0; i &lt; keys.length; i++) {
      if (keys[i].length &gt; ret)
        ret = keys[i].length; 
    }

    return ret;
  })();

  var getSpacer = function(len, state) {

    if (state.length &lt; len) {
      return getSpacer(len, state += ' ');
    } else {
      return state;
    }
  }

  for (i in obj) {
    console.log('%s: %s%s',
                i, 
                getSpacer(max - i.length, ''), 
                obj[i]);
  }
}
Simplification with for/in loops

Your loop through Object.keys() in the function you have for the max variable is reinventing JavaScript's for/in loop which loops over and objects keys. Here's how you could simplifying that code:

for(var key in obj) {
    if(!obj.hasOwnProperty(key)) {
        continue;
    }

    if(key.length &gt; ret) {
        ret = key.length;
    }
}




Unnecessary recursion

Your getSpacer function is using recursion when it really does not need to be; the function would be a lot simpler and a lot faster if you used a neat JavaScript trick for repeating characters:

function getSpacer(len) {
    return Array(len + 1).join(" ");
}


Now, there's no need for recursion - that means there is less interaction with the stack - and, rather than switching to a loop, this nice solution can be used.