This story on HackerNoon has a decentralized backup on Sia.
Transaction ID: uIKpsRmHcx-tdgN9T1AqsR6jcWLzVsApy3WPDi3Fq5c
Cover

How to Determine Whether a JavaScript Object Is Empty

Written by @smpnjn | Published on 2023/2/8

TL;DR
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? The easiest (and best) way to do this, is to use Object.keys().

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!

[story continues]


Written by
@smpnjn
Product, Engineering, Web

Topics and
tags
javascript|web-development|typescript|javascript-object-entries|javascript-development|javascript-tutorial|typescript-tutorial|tutorial
This story on HackerNoon has a decentralized backup on Sia.
Transaction ID: uIKpsRmHcx-tdgN9T1AqsR6jcWLzVsApy3WPDi3Fq5c