PLATFORM
  • Tails

    Create websites with TailwindCSS

  • Wave

    Start building the next great SAAS

  • Pines

    Alpine & Tailwind UI Library

  • Auth

    Plug'n Play Authentication for Laravel

  • Designer comingsoon

    Create website designs with AI

  • DevBlog comingsoon

    Blog platform for developers

  • Static

    Build a simple static website

  • SaaS Adventure

    21-day program to build a SAAS

How to Check if Object is Empty in JavaScript

How to Check if Object is Empty in JavaScript

Written by Johnny on Feb 4th, 2023 Views Report Post

Defining a new object in Javascript is pretty easy - but what if you want to find out if it's empty? For example, {} is an empty object, but how do we actually test that this is the case?

let myObject = {}

The easiest (and best) way to do this, is to use Object.keys(). This method turns all the keys in an object to an array, which we can then test the length of:

let myObject = {}

console.log(Object.keys(myObject).length) // Returns 0!

But wait... Javascript is well known for how it handles types strangely - and new constructors return an object with length 0:

let myFunction = function() {
    console.log("hello")
}
console.log(Object.keys(new myFunction()).length)

Fortunately, we can check if something is an object by checking its constructor property:

console.log(function myFunction() {}.constructor) // Function
console.log({}.constructor) // Object

Therefore, we can check if an object is empty if its constructor is an Object, and it has an Object.keys() value of 0:

let empty = {}
let isObjEmpty = (obj) => {
    return Object.keys(obj).length === 0 && obj.constructor === Object
}

console.log(isObjEmpty(empty)); // Returns true, Object is empty!

Comments (0)

loading comments