How to Use Object.keys in JavaScript: Syntax and Examples
Use
Object.keys(object) to get an array of all the object's own property names as strings. This method helps you list keys for any object, making it easy to loop through or inspect properties.Syntax
The syntax for Object.keys is simple:
object: The object whose own enumerable property names you want to get.- The method returns an array of strings representing the keys.
javascript
Object.keys(object)Example
This example shows how to use Object.keys to get all keys from an object and then loop through them to print each key and its value.
javascript
const person = { name: 'Alice', age: 30, city: 'New York' }; const keys = Object.keys(person); console.log(keys); // Prints all keys keys.forEach(key => { console.log(key + ': ' + person[key]); });
Output
["name", "age", "city"]
name: Alice
age: 30
city: New York
Common Pitfalls
One common mistake is expecting Object.keys to include inherited properties or non-enumerable properties. It only returns the object's own enumerable keys.
Also, if you pass a non-object (like null or undefined), it will throw an error.
javascript
const parent = { inherited: 'yes' }; const child = Object.create(parent); child.own = 'no'; console.log(Object.keys(child)); // ['own'] - does not include 'inherited' // Wrong usage example: try { Object.keys(null); } catch (e) { console.log('Error:', e.message); }
Output
["own"]
Error: Cannot convert undefined or null to object
Quick Reference
Object.keys Cheat Sheet:
- Returns an array of own enumerable property names.
- Does not include inherited or non-enumerable keys.
- Throws error if argument is
nullorundefined. - Useful for looping over object properties.
Key Takeaways
Object.keys(object) returns an array of the object's own enumerable property names.
It excludes inherited and non-enumerable properties.
Passing null or undefined to Object.keys throws an error.
Use the returned array to loop through or inspect object keys easily.