Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether it's safe to iterate over a JavaScript variable

Tags:

javascript

I have a JavaScript function where someone can pass anything in, and I iterate over each of its keys using the

for x in obj

syntax. However, this results in an error if they pass a primitive (string or number); the correct behavior is for the function to act the same way on those as it would on an object with no keys.

I can do a try..catch block to get around this, but is there another (more succinct) way?

like image 991
Trevor Burnham Avatar asked Jun 22 '10 22:06

Trevor Burnham


2 Answers

x && typeof(x) === 'object'

This is true for objects and arrays (though you usually don't want to iterate over arrays with for..in).

EDIT: Fix, per CMS.

like image 94
Matthew Flaschen Avatar answered Nov 14 '22 22:11

Matthew Flaschen


There's a number of ways you could infer that, here's a good one:

function isIterable(obj) {
  if (obj && obj.hasOwnProperty) {
    return true;
  }
  return false;
}

You could pick a number of them.

like image 20
Alex Sexton Avatar answered Nov 14 '22 21:11

Alex Sexton