14

I want to make an if statement to check if an object is an empty object or not.

By empty object I mean if I do console.log(object) it prints out {}.

How do I do this?

kynan
  • 13,235
  • 6
  • 79
  • 81
foothill
  • 483
  • 3
  • 8
  • 18
  • 1
    possible duplicate of [Is object empty?](http://stackoverflow.com/questions/4994201/is-object-empty) – Blender Jul 08 '13 at 21:29

2 Answers2

21
myObject = {}
if Object.keys(myObject).length == 0
    # myObject is "empty"
else
    # myObject is not "empty"
go-oleg
  • 19,272
  • 3
  • 43
  • 44
5

This function might work for you :

is_empty = (obj) ->
    return true if not obj? or obj.length is 0

    return false if obj.length? and obj.length > 0

    for key of obj
        return false if Object.prototype.hasOwnProperty.call(obj,key) 

    return true

#Examples
console.log is_empty("") #true
console.log is_empty([]) #true
console.log is_empty({}) #true
console.log is_empty(length: 0, custom_property: []) #true

console.log is_empty("Hello") #false
console.log is_empty([1,2,3]) #false
console.log is_empty({foo: 1}) #false
console.log is_empty(length: 3, custom_property: [1,2,3]) #false
warchimede
  • 878
  • 6
  • 7
  • 1
    Careful the object `{foo: undefined}` will return `true`, not `false` as you might expect. – Cimm Mar 07 '14 at 19:48