Different methods to check if Key exists in Object in JavaScript
In this tutorial we will explore following methods to check if key exists in an object in JavaScript with some simple as well as complex examples:
- Using the
in
operator - Using the
hasOwnProperty()
method - Using the
Object.keys()
method andincludes()
method - Using the
Object.getOwnPropertyNames()
method andincludes()
method - Using the
Object.getOwnPropertySymbols()
method andincludes()
method - Using the
Reflect.ownKeys()
method andincludes()
method
1. Use the in
operator
The operator in
checks for the presence of a property in an object or its prototype chain.
Syntax:
if ('key' in object) {
// Key exists
}
Simple Object Example:
const book = {
title: "1984",
author: "George Orwell"
};
console.log('title' in book); // true
console.log('author' in book); // true
console.log('published' in book); // false
Complex (Nested) Object Example:
const company = {
name: "Innovatech",
department: {
name: "Research",
head: "Alice Johnson"
}
};
console.log('name' in company); // true
console.log('head' in company.department); // true
console.log('budget' in company.department); // false
In the above example, even though company has a prototype with a budget property, using in would return true
.
2. Use the hasOwnProperty()
method
hasOwnProperty()
method checks if a property exists directly on the specified object without checking its prototype chain.
Syntax:
if (object.hasOwnProperty('key')) {
// Key exists as an own property
}
Simple Object Example:
const car = {
make: "Toyota",
model: "Corolla"
};
console.log(car.hasOwnProperty('make')); // true
console.log(car.hasOwnProperty('model')); // true
console.log(car.hasOwnProperty('year')); // false
Complex (Nested) Object Example:
const university = {
name: "State University",
faculty: {
arts: {
head: "Dr. Emily Rose"
},
science: {
head: "Dr. John Doe"
}
}
};
console.log(university.hasOwnProperty('name')); // true
console.log(university.hasOwnProperty('faculty')); // true
console.log(university.faculty.hasOwnProperty('arts')); // true
console.log(university.faculty.arts.hasOwnProperty('head')); // true
console.log(university.faculty.hasOwnProperty('budget')); // false
The hasOwnProperty()
, only checks properties that belong to the object itself, not inherited ones. This method is useful when you want to make sure that a property is an own property of the object especially when you deal with objects that might have been extended or are using with prototypes.
3. Use the Object.keys()
and includes()
methods
Object.keys()
returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by iterating over the properties of the object manually.
Syntax:
if (Object.keys(object).includes('key')) {
// Key exists and is enumerable
}
Simple Object Example:
const person = {
name: "Sarah",
age: 25
};
// Checking for property existence
const hasName = Object.keys(person).includes('name'); // true
const hasOccupation = Object.keys(person).includes('occupation'); // false
console.log(hasName); // Outputs: true
console.log(hasOccupation); // Outputs: false
Complex (Nested) Object Example:
const product = {
id: 101,
details: {
price: 29.99,
stock: 120
}
};
// Checking for property in nested object
const hasPrice = Object.keys(product.details).includes('price'); // true
const hasDiscount = Object.keys(product.details).includes('discount'); // false
console.log(hasPrice); // Outputs: true
console.log(hasDiscount); // Outputs: false
4. Using the Object.getOwnPropertyNames()
method and includes()
method
Object.getOwnPropertyNames()
returns an array whose elements are strings corresponding to the non-enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over them manually.
Syntax:
if (Object.getOwnPropertyNames(object).includes('key')) {
// Key exists, whether enumerable or not
}
Simple Object Example:
const vehicle = {
make: "Honda"
};
Object.defineProperty(vehicle, 'hiddenFeature', {
value: 'secret',
enumerable: false
});
// Checking for both enumerable and non-enumerable properties
const hasMake = Object.getOwnPropertyNames(vehicle).includes('make'); // true
const hasHiddenFeature = Object.getOwnPropertyNames(vehicle).includes('hiddenFeature'); // true
console.log(hasMake); // Outputs: true
console.log(hasHiddenFeature); // Outputs: true
Complex (Nested) Object Example:
const company = {
name: "Tech Corp",
department: {
name: "Development"
}
};
Object.defineProperty(company.department, 'internalCode', {
value: 'X123',
enumerable: false
});
// Checking for property existence including non-enumerable
const hasDepartmentName = Object.getOwnPropertyNames(company.department).includes('name'); // true
const hasInternalCode = Object.getOwnPropertyNames(company.department).includes('internalCode'); // true
console.log(hasDepartmentName); // Outputs: true
console.log(hasInternalCode); // Outputs: true
5. Using the Object.getOwnPropertySymbols()
method and includes()
method
Object.getOwnPropertySymbols()
retrieves all symbol properties found directly on a given object. This method is very useful for handling or checking for properties that use symbols.
Syntax:
if (Object.getOwnPropertySymbols(object).includes(symbolKey)) {
// Symbol key exists
}
Simple Object Example:
const user = {
name: "John",
[Symbol('password')]: "12345"
};
const symbols = Object.getOwnPropertySymbols(user);
const hasPasswordSymbol = symbols.includes(symbols.find(sym => sym.description === 'password')); // true
console.log(hasPasswordSymbol); // Outputs: true
Complex (Nested) Object Example:
const settings = {
level: 1,
options: {
[Symbol('secret')]: "hidden_value"
}
};
const optionSymbols = Object.getOwnPropertySymbols(settings.options);
const hasSecretSymbol = optionSymbols.includes(optionSymbols.find(sym => sym.description === 'secret')); // true
console.log(hasSecretSymbol); // Outputs: true
Object.getOwnPropertySymbols()
is crucial when your objects make use of symbol keys and you need to perform operations based on these keys.
6. Using the Reflect.ownKeys()
method and includes()
method
Reflect.ownKeys()
returns all keys in the object. This includes both symbol and string keys, and regardless of whether they are enumerable. This method allows for an introspection into an object. It is especially useful when debugging or developing an application where it is necessary to see all of its structure.
Syntax:
if (Reflect.ownKeys(object).includes('key')) {
// Key exists, including symbols and non-enumerables
}
Here's an example:
const company = {
name: "Tech Solutions",
department: {
employees: 250
}
};
Object.defineProperty(company.department, 'budget', {
value: 1000000,
enumerable: false
});
const departmentSymbols = Symbol('internalCode');
company.department[departmentSymbols] = "Dept01";
const departmentKeys = Reflect.ownKeys(company.department);
const hasEmployees = departmentKeys.includes('employees'); // true
const hasBudget = departmentKeys.includes('budget'); // true
const hasInternalCode = departmentKeys.includes(departmentSymbols); // true
console.log(hasEmployees); // Outputs: true
console.log(hasBudget); // Outputs: true
console.log(hasInternalCode); // Outputs: true
Reflect.ownKeys() provides a complete picture of an object's keys. It is the most comprehensive way to check property values, since it covers all types (enumerable and non-enumerable properties, as well as string and symbol properties).
Frequently Asked Questions
What is the difference between hasOwnProperty
and the in
operator?
hasOwnProperty
checks if the key exists as the object's own property, ignoring the prototype chain. The in
operator checks for the key's existence both on the object and up its prototype chain.
Can I use the in
operator for arrays?
Yes, you can. In arrays, the in
operator checks if a particular index exists, not the value itself. For example, for the array ['apple', 'banana']
, '0 in array'
would return true
.
How can I check for nested keys without getting a TypeError?
You can use conditional checks to validate each level of nesting before proceeding to the next. Alternatively, use JavaScript's optional chaining (?.
) to safely navigate nested keys.
Is it possible to check for a key in a Map object?
Yes, Maps in JavaScript have a has
method explicitly designed for this purpose. For instance, if you have a Map called myMap
, you can check for a key by calling myMap.has(key)
.
How do I check for a key's existence in a Set?
Sets don't have keys in the way objects and arrays do. They only contain unique values. You can use the has
method to check for a value's existence in a Set. For example, mySet.has(value)
.
Is it better to check for a key's existence before accessing it, or should I catch the error later?
It's generally better to check for a key's existence before attempting to access its value to avoid runtime errors, unless you have a specific reason for catching errors (e.g., logging).
How can I check for multiple keys at once?
You can use a loop or methods like Array.every()
along with hasOwnProperty
or in
to check for the existence of multiple keys in an object.
Can I use Object.keys()
to check for keys in a nested object?
No, Object.keys()
only returns an array of an object's own enumerable properties. It won't check for keys in nested objects. You'll have to navigate to the nested object first and then use Object.keys()
.
How do null
and undefined
affect key existence checks?
A key can exist with a value of undefined
or null
. Using hasOwnProperty
or in
will return true
in these cases. Checking the value directly may give you the wrong impression that the key does not exist.
What is the most performance-efficient way to check for key existence in large objects?
For large objects, using hasOwnProperty
is generally the most performance-efficient because it operates in constant time, O(1).
Summary
In JavaScript, it is common to check if a given object has a key; there are many ways to go about this. The most popularly used ones include the in
operator and hasOwnProperty()
method that test for presence of keys on the object itself but not those found on the prototype chain of the object.
For more advanced scenarios, there are methods like Object.keys()
, Object.getOwnPropertyNames()
, Object.getOwnPropertySymbols()
, and Reflect.ownKeys()
. These methods return an array of all keys, including those found on an object’s prototype chain. To find out if any key exists within the returned array, these methods can be paired with includes()
or indexOf()
.
Object.getOwnPropertyNames()
can prove useful especially when checking for non-enumerable keys’ existence. While working with symbol keys, which are one of their kind and not accessible via string index, one may consider using Object.getOwnPropertySymbols()
. The best choice should be using Reflect.ownKeys()
, since it takes into account all types of keys, symbols as well as strings.
Additional Resources
Object.prototype.hasOwnProperty() - JavaScript | MDN (mozilla.org)
in operator - JavaScript | MDN (mozilla.org)
Object.keys() - JavaScript | MDN (mozilla.org)