Sunday, April 15, 2012

Javascript - Object.keys Browser Compatibility

For Object.keys compatibility in all browsers add this code before using Object.keys.

if (!Object.keys) Object.keys = function(o) {
  if (o !== Object(o))
    throw new TypeError('Object.keys called on a non-object');
  var k=[],p;
  for (p in o) if (,p)) k.push(p);
  return k;

You can now use Object.keys as normal such as Object.keys(myObject).length
Anonymous said...

Why are you doing,p) instead of a simple o.hasOwnProperty(p)? Is it just in case that method is overridden in o?

Craig Constable said...

From memory o.hasOwnProperty(p) does not work correctly in IE < 9

Unknown said...


Which information given by you on JavaScript-Browser Compatibility, very informative. So thanks for sharing your

knowledge. There are few other link that's also helpful for developers.

Anonymous said...

thanks alot...

garvan said...

I don't believe for in loops work in IE8, so while this should solve the issue theoretically, it may introduce another problem.

Sam R said...

@garvan - for-in was added in Internet Explorer 5.

Unknown said...


Anonymous said...
This comment has been removed by a blog administrator.

Post a Comment