Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
How to Create an Object in TypeScript?
Next article icon

How to Check if an Object is Empty in TypeScript ?

Last Updated : 12 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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()

Using Object.keys()

This approach involves using the Object.keys() method to extract all the keys of the object and then checking the length of the resulting array.

Example: In this example, we create an empty object `myObject` and then use the `Object.keys()` method to check if it is empty.

JavaScript
const obj1: Record<string, any> = {}; const obj2: Record<string, any> =   { name: "John", age: 30 };  if (Object.keys(obj1).length === 0) {   console.log('obj1 is empty');  } else {   console.log('obj1 is not empty'); }  if (Object.keys(obj2).length === 0) {   console.log('obj2 is empty'); } else {   console.log('obj2 is not empty');  } 

Output:

obj1 is empty obj2 is not empty 

Using Object.entries()

This approach utilizes the Object.entries() method to get an array of key-value pairs from the object and then checks the length of the array.

Example: This example shows the use of the above-explained approach.

JavaScript
const obj3: Record<string, any> = {}; const obj4: Record<string, any> =   { name: "Alice", city: "New York" };  if (Object.entries(obj3).length === 0) {   console.log('obj3 is empty');  } else {   console.log('obj3 is not empty'); }  if (Object.entries(obj4).length === 0) {   console.log('obj4 is empty'); } else {   console.log('obj4 is not empty');  } 

Output:

obj3 is empty obj4 is not empty 

Using a for...in loop

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.

JavaScript
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 

Using JSON.stringify()

Converting the object into a JSON string allows for easy checking if it's empty by verifying the length of the resulting string.

Example: This example shows the use of the above-explained approach.

JavaScript
const obj7: Record<string, any> = {}; const obj8: Record<string, any> =   { language: "TypeScript", version: "4.5" };  if (JSON.stringify(obj7) === '{}') {   console.log('obj7 is empty');  } else {   console.log('obj7 is not empty'); }  if (JSON.stringify(obj8) === '{}') {   console.log('obj8 is empty'); } else {   console.log('obj8 is not empty');  } 

Output:

obj7 is empty obj8 is not empty 

Next Article
How to Create an Object in TypeScript?

B

bhosaleaniket2707
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • TypeScript

Similar Reads

  • Check if an Object is Empty in TypeScript
    In TypeScript, determining whether an object is empty involves checking if the object has any properties. This can be achieved through various built-in methods and loops. In this article, we will explore three different approaches to check if an object is empty in TypeScript. Table of Content Using
    2 min read
  • Check if an Array is Empty or not in TypeScript
    In TypeScript, while performing any operation on the array, it is quite important that there should be elements or data in the array, else no operation can be done. We can check whether the array contains the elements or not by using the below-listed methods: Table of Content Using length PropertyUs
    2 min read
  • How to Check if an Array Includes an Object in TypeScript ?
    In TypeScript, checking if an array includes an object consists of comparing the object's properties within the array elements. We can compare and check this using three different approaches some method, find method, and includes method. There are several ways to check if an array includes an object
    3 min read
  • How to Check if all Enum Values Exist in an Object in TypeScript ?
    To check if all values of an enum exist in an object in TypeScript, iterate through the enum values and verify their presence in the object. This ensures that the object encompasses all possible enum values, confirming completeness and adherence to the enum definition. There are various methods to c
    3 min read
  • How to Create an Object in TypeScript?
    TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data. Creating Objects in TypescriptNow, let
    4 min read
  • How to Return an Empty Promise in TypeScript ?
    In TypeScript, you can return an empty promise to create an empty asynchronous task. There are mainly two ways that can be used to create empty promises in TypeScript as listed below. Table of Content By using the Promise.resolve() methodBy immediately resolving the promiseUsing async/await to Retur
    2 min read
  • How to Check the Type of an Object in Typescript ?
    When working with TypeScript, understanding how to check the type of an object is crucial for ensuring type safety and maintaining code integrity. TypeScript, being a statically typed superset of JavaScript, provides several approaches to accomplish this task as listed below. Table of Content Using
    3 min read
  • How to Get an Object Value By Key in TypeScript
    In TypeScript, we can get an object value by key by accessing the specific properties within the objects of the dynamic type. This can be done using Dot Notation, Bracket Notation, and Optional Chaining. In this article, we will explore all these approaches along with their implementation in terms o
    5 min read
  • How to Check an Object is Empty using JavaScript?
    These are the following ways that can be used to Check an Object is Empty using JavaScript: 1. Using Object.keys() Method - Mostly usedThe Object.keys() method returns an array that contains the property names of an object. If the length of array is 0, then object is empty. [GFGTABS] JavaScript let
    2 min read
  • How to Check if a Key Exists in a Dictionary in TypeScript ?
    In TypeScript dictionaries are used whenever the data is needed to be stored in key and value form. We often retrieve the data from the dictionaries using an associated key. Therefore it becomes crucial to check whether the key exists in a dictionary or not. We can use the below methods to check if
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences