What is the method to check if a JavaScript object is empty

0 votes
With the help of proper code, can you tell me What the method is to check if a JavaScript object is empty?
Jan 10 in Java-Script by Ashutosh
• 20,870 points
95 views

1 answer to this question.

0 votes

You can use several methods:

1. Using Object.keys()

const isEmpty = (obj) => {

  return Object.keys(obj).length === 0 && obj.constructor === Object;

};

2. Using a for...in Loop

const isEmpty = (obj) => {

  for (let prop in obj) {

    if (obj.hasOwnProperty(prop)) {

      return false;

    }

  }

  return true;

};

3.Using JSON.stringify()

const isEmpty = (obj) => {

  return JSON.stringify(obj) === '{}';

};

answered Feb 7 by Navya

Related Questions In Java-Script

0 votes
1 answer
0 votes
1 answer

How to list the properties of a JavaScript object?

Hii @kartik, Use Reflect.ownKeys(): var obj = {a: 1, b: ...READ MORE

answered Jun 8, 2020 in Java-Script by Niroj
• 82,840 points
1,127 views
0 votes
1 answer

How to check if the URL contains a given string?

Hello @kartik, You would use indexOf like this: if(window.location.href.indexOf("franky") != -1){....} Also ...READ MORE

answered Jun 11, 2020 in Java-Script by Niroj
• 82,840 points
6,974 views
0 votes
1 answer

How to run an HTML file using Node.js?

1.Install Node.js 2.Create a Project Folder mkdir html-node-app cd html-node-app 3.Initialize ...READ MORE

answered Feb 12 in Node-js by Navya
57 views
0 votes
1 answer

How can I dynamically validate Angular forms based on user input?

Dynamic Form Controls with Validation: In scenarios where ...READ MORE

answered Feb 12 in Angular by Navya
68 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP