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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With