Check if object is empty using JavaScript with .hasownproperty() and object.keys().
0 2184
In this tutorial, we are going to explain the code to check if an object is empty using JavaScript. While writing codes and developing logic in between, sometimes it required to check if an object is empty or not.
There are many methods in JavaScript which can solve this for us. I am going to explain two of them using examples. These are:
Object.keys() Object.hasOwnProperty(): Looping through the object
Let's start
1 Object.keys() Method
The first method is the Object.keys() Method. Let’s first learn the syntax of this.
Syntax: Object.Keys(object). The parameter which this method takes is an object itself, which means the object of which own properties are to be returned. We are using Length property to check if the object has keys in it. The output is directed to the console.
Note: this method does not support older browsers.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>The Object.keys() Method</title> </head> <body> <h1>The Object.keys() Method</h1> <script type="text/javascript"> //javascript empty object let Letobj = {}; function isEmpty(object) { return Object.keys(object).length === 0; } let emptyObj = isEmpty(Letobj); console.log(emptyObj); </script> </body> </html>
Output:
See a Boolean value "TRUE" represents that object is empty.
2 Object.hasOwnProperty() Method: Looping through the object
The second solution is using Object.hasownproperty().
Syntax: Object.hasOwnProperty(prop). Here the parameter passed is a prop which is the name of the property to test.
Code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Using Object.hasOwnProperty() Method</title> </head> <body> <h1>Using Object.hasOwnProperty() Method</h1> <script type="text/javascript"> let obj = {name: 'Coding Tag'}; function isEmptyObj(obj) { for (let key in obj) { if (obj.hasOwnProperty(key)) { return false; } } } let emptyObj = isEmptyObj(obj); console.log(emptyObj); </script> </body> </html>
Output:
See a Boolean value "FALSE" represents that object is not empty.
I hope you have understood both the methods to check if the string is empty.
Please leave a comment if you find this blog useful . Do subscribe to our website for more solutions.
Share:
Comments
Waiting for your comments