0

I have code like this:

function doAThing(var1) {
    return typeof var1 === "object" && Object.keys(var1).length > 11;
}

I'm having a problem where when var1 is NOT an object the function tries to return the value of the last statement: Object.keys(var1).length > 11)

Obviously, if obj1 is not an object i don't want to try and get it's keys or it will blow up with Cannot convert undefined or null to object.

How can i get this function to return a boolean and NOT try to check var1's keys if it's not an object?

Billy Blob Snortin
  • 1,101
  • 3
  • 11
  • 17
  • 3
    Actually, the last condition shouldn't be evaluated as it shortcuts on the first `false` - see http://stackoverflow.com/questions/7858787/does-javascript-use-optimization-in-boolean-expressions Can you post the complete code causing your issue and tell us what 'blow up' actually means (what error do you encounter)? – le_m May 20 '17 at 01:51
  • not sure you can shortcut as Object.keys will be evaluated anyway. – cpugourou May 20 '17 at 01:56
  • @cpugourou I wouldn't think so if it's following the truthy/falsy logic which it should be. Are you sure it would evaluate? – War10ck May 20 '17 at 01:57
  • Updated. If you cannot shortcut what would you suggest as an alternate? – Billy Blob Snortin May 20 '17 at 01:57
  • Note that your `typeof` will not return the desired results in some cases. For instance, if `var1` is an array, `typeof var1` will still be `object`. See [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof) for more details. – War10ck May 20 '17 at 02:01

1 Answers1

4

Try adding a null check to your condition, as typeof null is also object:

function doAThing() {
    return !bool1
        && var1 !== null
        && typeof var1 === "object"
        && Object.keys(var1).length > 11);
}
m1kael
  • 2,801
  • 1
  • 15
  • 14