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
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to check whether a number is NaN or finite in JavaScript ?
Next article icon

How to check whether an object exists in javascript ?

Last Updated : 24 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Checking whether an object exists in JavaScript refers to determining if a variable or property has been declared and contains a valid value. This helps avoid errors when accessing or manipulating objects that may be undefined, null, or not initialized properly.

Here we have some common approaches to check whether an object exists in javascript:

Table of Content

  • Using the typeof operator
  • Using try-catch to catch Reference error

Method 1: Using the typeof operator

The typeof operator in JavaScript returns the type of a variable as a string. If an object doesn’t exist, typeof will return undefined. This approach helps determine if a variable or object has been declared without causing runtime errors.

Syntax: 

if (typeof objectToBeTested != "undefined")      // object exists  else     // object does not exist 

Example: In this example, we checks if an object exists in JavaScript using the typeof operator. When the button is clicked, it verifies if both an existing and non-existing object are defined,

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width,                     initial-scale=1.0">     <title>Using the typeof operator</title> </head>  <body>     <h1 style="color: green">         GeeksforGeeks     </h1>     <b>How to check whether an         object exists in javascript</b>      <p>Click on the button to         check if the object exists</p>      <p>Output for existing object:         <span class="outputExist"></span>     </p>     <p>Output for non existing object:         <span class="outputNonExist"></span>     </p>      <button onclick="checkObjectExists()">         Click here     </button>     <script type="text/javascript">         function checkObjectExists() {             // create an existing object for comparison              let existingObject = {};              if (typeof existingObject != "undefined") {                 ans = true;             } else {                 ans = false             }              document.querySelector(                 '.outputExist').textContent = ans;              if (typeof nonExistingObject != "undefined") {                 ans = true;             } else {                 ans = false;             }              document.querySelector(                 '.outputNonExist').textContent = ans;         }      </script> </body>  </html> 

Output:

How to check whether an object exists in javascript ?

Using the typeof operator to check whether an object exists

Method 2: Using try-catch to catch Reference error

The try-catch approach in JavaScript checks if an object exists by attempting to access its properties. If the object doesn’t exist, a ReferenceError is thrown, which the catch block handles, allowing graceful detection of missing or undefined objects.

Syntax: 

try {     objectToBeTested.prop;     // object exists } catch {     // object does not exist }

Example: In this example, we a try-catch block to check whether an object exists in JavaScript. When the button is clicked, it verifies both an existing and non-existing object,

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width,                     initial-scale=1.0">     <title>Using try-catch to catch Reference error</title> </head>  <body>     <h1 style="color: green">         GeeksforGeeks     </h1>     <b>How to check whether an         object exists in javascript</b>      <p>Click on the button to check         if the object exists</p>     <p>Output for existing object:         <span class="outputExist"></span>     </p>      <p>Output for non existing object:         <span class="outputNonExist"></span>     </p>      <button onclick="checkObjectExists()">Click here</button>     <script type="text/javascript">         function checkObjectExists() {              // create an existing object for comparison              let existingObject = {};              try {                 // accessing a random property                  existingObject.prop;                 ans = true;             } catch {                 ans = false;             }              document.querySelector(                 '.outputExist').textContent = ans;              try {                 // accessing a random property                  nonExistingObject.prop;                 ans = true;             } catch {                 ans = false;             }              document.querySelector(                 '.outputNonExist').textContent = ans;          }      </script> </body>  </html> 

Output:

How to check whether an object exists in javascript ?

Using try-catch to catch Reference error to check whether an object exists



Next Article
How to check whether a number is NaN or finite in JavaScript ?
author
sayantanm19
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • How to Check a Key Exists in JavaScript Object?
    Here are different ways to check a key exists in an object in JavaScript. Note: Objects in JavaScript are non-primitive data types that hold an unordered collection of key-value pairs. 1. Using in Operator The in operator in JavaScript checks if a key exists in an object by returning a boolean value
    2 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 Whether an Object is a Date ?
    This article will show you how to check whether the given object is a Date or not. There are two methods to check for date objects, which are described below: Method 1: Using instanceof Operator The instanceof operator checks whether the prototype property of a constructor appears anywhere in the pr
    2 min read
  • How to check whether a number is NaN or finite in JavaScript ?
    When working with numbers in JavaScript, it's important to know how to determine if a value is NaN (Not-a-Number) or finite. This knowledge is crucial for data validation, error handling, and ensuring your code behaves as expected. In this article, we will see how to check whether the number is NaN
    3 min read
  • How to Check Object is an Array in JavaScript?
    There are two different approaches to check an object is an array or not in JavaScript. 1. Using Array.isArray() MethodThe Array.isArray() method determines whether the value passed to this function is an array or not. This method returns true if the argument passed is an array else it returns false
    1 min read
  • How to get the Class Name of an Object in JavaScript
    In this article, we will learn how we can get the class Name of an Object with multiple approaches in JavaScript. In JavaScript, determining an object's class name can be done using multiple approaches. The constructor property of an object reveals the function that created it, while the instanceof
    3 min read
  • How to check a JavaScript Object is a DOM Object ?
    Checking if a JavaScript object is a DOM object involves verifying whether the object represents an element or component within the Document Object Model (DOM) of an HTML or XML document. This can be done by checking if the object is an instance of Node, Element, or other specific DOM interfaces. Wh
    2 min read
  • How to Check an Element with Specific ID Exists using JavaScript ?
    Given an HTML document containing some elements and the elements contain some id attribute. The task is to check whether the element with a specific ID exists or not using JavaScript. Below are the approaches to check an element with specific ID exists or not using JavaScript:  Table of Content Appr
    3 min read
  • How to check the type of a variable or object in JavaScript ?
    In this article, How to Check the Type of a Variable or Object in JavaScript? In JavaScript, the typeof operator is used to determine the typeof an object or variable. JavaScript, on the other hand, is a dynamically typed (or weakly typed) language. This indicates that a variable can have any type o
    2 min read
  • How to check if a value is object-like in JavaScript ?
    In JavaScript, objects are a collection of related data. It is also a container for name-value pairs. In JavaScript, we can check the type of value in many ways. Basically, we check if a value is object-like using typeof, instanceof, constructor, and Object.prototype.toString.call(k). All of the ope
    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