Search code examples
javascriptecmascript-5

What is wrong with this way of checking if an object is empty?


function isEmpty(obj) {
  for(var key in obj) {
    return false;
    }
    return true;
}

What is wrong with this way of checking if an object is empty? I'm fairly new to JS and I'm going through SO to check what is the best and fastest way of checking if an object is empty and came across is this How do I test for an empty JavaScript object? among others.

All questions have similar answers checking Object.prototype.hasOwnProperty which seems unnecessarily complicated. Is there a use-case where the code I've provided won't work and I should use the answers provided in the linked questions?


Solution

  • Consider the following case:

    const foo = { a: 1 }
    const bar = {}
    Object.setPrototypeOf(bar, foo)
    console.log(bar) // {}
    for (let key in bar) console.log(key) // logs a!!
    

    That is what I meant in the comment about walking the prototype chain.

    Consider also this:

    const foo = {}
    Object.defineProperty(foo, 'a', {
      enumerable: false,
      value: 1,
    })
    console.log(foo.a) // 1
    for (let key in foo) console.log(key) // doesn't log anything!
    

    So that's two edge cases your function misses. You probably don't want to log anything in the first example, and you probably do want to log the key in the second.