Algorithm


  1. Initialize Object:

    • Create or have an existing JavaScript object.
  2. Check if Key Exists Algorithm:

    • Define a function, e.g., keyExists(object, keyToCheck).
    • Use the hasOwnProperty method or the in operator to check if keyToCheck exists in object.
    • Return true if the key exists, otherwise return false.
  3. Usage:

    • Call the keyExists function with the object and the key you want to check.

 

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

x
+
cmd
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

x
+
cmd
The key exists.
Advertisements

Demonstration


JavaScript Programing Example to Check if a Key Exists in an Object-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way