Algorithm
-
Initialize Object:
- Create or have an existing JavaScript object.
-
Check if Key Exists Algorithm:
- Define a function, e.g.,
keyExists(object, keyToCheck)
. - Use the
hasOwnProperty
method or thein
operator to check ifkeyToCheck
exists inobject
. - Return
true
if the key exists, otherwise returnfalse
.
- Define a function, e.g.,
-
Usage:
- Call the
keyExists
function with the object and the key you want to check.
- Call the
Code Examples
#1 Code Example- Check if Key Exists in Object Using in Operator
Code -
Javascript Programming
// program to check if a key exists
const person = {
id: 1,
name: 'John',
age: 23
}
// check if key exists
const hasKey = 'name' in person;
if(hasKey) {
console.log('The key exists.');
}
else {
console.log('The key does not exist.');
}
Copy The Code &
Try With Live Editor
Output
The key exists.
#2 Code Example- Check if Key Exists in Object Using hasOwnProperty()
Code -
Javascript Programming
// program to check if a key exists
const person = {
id: 1,
name: 'John',
age: 23
}
//check if key exists
const hasKey = person.hasOwnProperty('name');
if(hasKey) {
console.log('The key exists.');
}
else {
console.log('The key does not exist.');
}
Copy The Code &
Try With Live Editor
Output
The key exists.
Demonstration
JavaScript Programing Example to Check if a Key Exists in an Object-DevsEnv