How to use a for…in loop In Typescript
By iterating through all enumerable properties of the object using a for…in loop, this approach checks if the object has any enumerable properties.
Example: This example shows the use of the above-explained approach.
const obj5: Record<string, any> = {};
const obj6: Record<string, any> =
{ fruit: "Apple", quantity: 5 };
function isEmpty(obj: Record<string, any>): boolean {
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
}
if (isEmpty(obj5)) {
console.log('obj5 is empty');
} else {
console.log('obj5 is not empty');
}
if (isEmpty(obj6)) {
console.log('obj6 is empty');
} else {
console.log('obj6 is not empty');
}
Output:
obj5 is empty
obj6 is not empty
How to Check if an Object is Empty in TypeScript ?
In TypeScript, it’s common to encounter scenarios where you need to determine if an object is empty or not. An empty object typically means it contains no properties or all its properties are either undefined or null.
Below are the methods to check if an object is empty or not in TypeScript:
Table of Content
- Using Object.keys()
- Using Object.entries()
- Using a for…in loop
- Using JSON.stringify()
Contact Us