How to check whether an object exists in javascript ?
Last Updated :
24 Sep, 2024
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:
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:
Using the typeof operator to check whether an object existsMethod 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:
Using try-catch to catch Reference error to check whether an object exists
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. check a key exists in JavaScript object1. Using in Operator The in operator in JavaScript checks if a key exists in
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.JavaScriptlet obj = {}; if
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 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 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.Wha
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 ContentApproa
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
How to Check if an Object has a Specific Property in JavaScript ? In JavaScript, objects can have properties that store data or functions. Sometimes it is necessary to check whether an object has a specific property. This can be useful, for example, when you want to avoid calling a function on an object that doesn't have that function defined as a property. In thi
3 min read
How to Detect an Undefined Object Property in JavaScript ? Detecting an undefined object property is the process of determining whether an object contains a certain property, and if it does, whether the value of that property is undefined. This is an important concept in JavaScript programming, as it helps to prevent errors that can occur when attempting to
3 min read