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?

5
  • 3
    Actually, the last condition shouldn't be evaluated as it shortcuts on the first false - see stackoverflow.com/questions/7858787/… Can you post the complete code causing your issue and tell us what 'blow up' actually means (what error do you encounter)? Commented May 20, 2017 at 1:51
  • not sure you can shortcut as Object.keys will be evaluated anyway. Commented May 20, 2017 at 1: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? Commented May 20, 2017 at 1:57
  • Updated. If you cannot shortcut what would you suggest as an alternate? Commented May 20, 2017 at 1: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 for more details. Commented May 20, 2017 at 2:01

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.