How can I check if a key exists in JavaScript?

author
0 minutes, 16 seconds Read
0
admin
Mar 07, 2024 01:31 PM 0 Answers
Member Since Feb 2024
Subscribed Subscribe Not subscribe
Flag(0)
// Sample object
const obj = {
key1: 'value1',
key2: 'value2',
key3: 'value3'
};

// Function to check if key exists
function keyExists(obj, key) {
return obj.hasOwnProperty(key);
}

// Example usage
const keyToCheck = 'key2';
if (keyExists(obj, keyToCheck)) {
console.log(`Key "${keyToCheck}" exists in the object.`);
} else {
console.log(`Key "${keyToCheck}" does not exist in the object.`);
}
0 Subscribers
Submit Answer
0 Answers
Sort By:

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

X