How to use the typeof operator In Javascript
Although it’s not a foolproof method for checking if a key exists in an object, you can use the typeof operator to check if a property is defined in an object. This method checks if the value associated with the key is not undefined.
Syntax:
typeof operand
// OR
typeof (operand)
Example: In this example, we check if the keys ‘name’ and ‘remarks’ exist in the object ‘exampleObj’. It evaluates to false for ‘name’ and true for ‘remarks’.
let exampleObj = {
id: 1,
remarks: 'Good'
};
// Check for the keys
let output1 = typeof exampleObj['name'] !== 'undefined';
let output2 = typeof exampleObj['remarks'] !== 'undefined';
console.log(output1); // false
console.log(output2); // true
Output
false true
How to Check a Key Exists in JavaScript Object ?
Checking if a key exists in a JavaScript object involves verifying whether a specific property is defined within the object. This practice ensures data integrity, prevents errors, and facilitates smooth program execution by confirming property existence before accessing or manipulating it.
Objects in JavaScript are non-primitive data types that hold an unordered collection of key-value pairs. Here, we have an object and we need to check whether the given key is present in the given object or not.
Lets create a JavaScript object having with given key-values and then we will explore different approaches to check a key exist in the Object.
// Given object
let exampleObj = {
id: 1,
remarks: 'Good'
}
Here are some common approaches to Check if a Key Exists in an Object:
Table of Content
- Using in operator
- Using hasOwnProperty() method
- Using the Object.keys method
- Using the typeof operator