How to use object.hasOwnProperty(key) In Javascript
A function can be created to loop over the object and check if it contains any properties using the object.hasOwnProperty(key)
method. This method is particularly useful for older browsers that may not support Object.keys()
.
Syntax:
function isEmptyObj(object) {
for (var key in object) {
if (object.hasOwnProperty(key)) {
return false;
}
}
}
Example:
<!DOCTYPE html>
<html>
<head>
<title>
How to check an object is
empty using JavaScript?
</title>
</head>
<body>
<h1 style="color: green">
w3wiki
</h1>
<b>
How to check an object is
empty using JavaScript?
</b>
<p>
on the button to check
if the object is empty
</p>
<p>
Output for empty object:
<span class="outputEmpty"></span>
</p>
<p>
Output for non empty object:
<span class="outputNonEmpty"></span>
</p>
<button onclick="checkObject()">
Click here
</button>
<script type="text/javascript">
function checkObject() {
let emptyObj = {}
let nonEmptyObj = {
title: 'Title 1',
info: 'Sample Info'
}
ans1 = isEmptyObj(emptyObj);
document.querySelector('.outputEmpty').textContent
= ans1;
ans2 = isEmptyObj(nonEmptyObj);
document.querySelector('.outputNonEmpty').textContent
= ans2;
}
function isEmptyObj(object) {
for (var key in object) {
if (object.hasOwnProperty(key)) {
return false;
}
}
return true;
}
</script>
</body>
</html>
Output:
How to check an object is empty using JavaScript?
Checking whether an object is empty in JavaScript is a common task in programming. An empty object typically refers to one that doesn’t contain any own properties. This verification is essential for ensuring data integrity, handling edge cases, and implementing conditional logic in applications.