Check if it is safe to loop through a JavaScript variable

I have a JavaScript function in which someone can pass something and I iterate over each of his keys with

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 in exactly the same way as on an object without keys.

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

+7
javascript
source share
2 answers
 x && typeof(x) === 'object' 

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

EDIT: Correct, per CMS.

+7
source share

There are several ways to conclude that here is a good one:

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

You can choose several of them.

+2
source share

All Articles